summaryrefslogtreecommitdiff
path: root/spec
diff options
context:
space:
mode:
Diffstat (limited to 'spec')
-rw-r--r--spec/data/client.d_00/02-strings.rb2
-rw-r--r--spec/data/mixin/invalid_data.rb3
-rw-r--r--spec/data/mixin/real_data.rb2
-rwxr-xr-xspec/functional/assets/chefinittest10
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.aarch64.rpmbin0 -> 2096 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.i686.rpmbin6530 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.src.rpmbin6331 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpmbin6498 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.i686.rpmbin0 -> 2148 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64.rpmbin0 -> 2118 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64le.rpmbin0 -> 2098 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.s390x.rpmbin0 -> 2102 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.src.rpmbin0 -> 2132 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.10-1.x86_64.rpmbin0 -> 2110 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.aarch64.rpmbin0 -> 2096 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.i686.rpmbin6526 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.src.rpmbin6331 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpmbin6494 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.i686.rpmbin0 -> 2149 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64.rpmbin0 -> 2119 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64le.rpmbin0 -> 2098 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.s390x.rpmbin0 -> 2102 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.src.rpmbin0 -> 2133 bytes
-rw-r--r--spec/functional/assets/yumrepo/chef_rpm-1.2-1.x86_64.rpmbin0 -> 2113 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0-primary.sqlite.bz2bin2460 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553-other.xml.gzbin413 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/4632d67cb92636e7575d911c24f0e04d3505a944e97c483abe0c3e73a7c62d33-filelists.sqlite.bz2bin0 -> 1322 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773-filelists.sqlite.bz2bin1131 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243-primary.xml.gzbin859 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/74599b793e54d877323837d2d81a1c3c594c44e4335f9528234bb490f7b9b439-other.xml.gzbin0 -> 502 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16-filelists.xml.gzbin419 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/a845d418f919d2115ab95a56b2c76f6825ad0d0bede49181a55c04f58995d057-primary.sqlite.bz2bin0 -> 2569 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/af9b7cf9ef23bd7b43068d74a460f3b5d06753d638e58e4a0c9edc35bfb9cdc4-other.sqlite.bz2bin0 -> 1115 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc-other.sqlite.bz2bin967 -> 0 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/bdb4f5f1492a3b9532f22c43110a81500dd744f23da0aec5c33b2a41317c737d-filelists.xml.gzbin0 -> 529 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/c10d1d34ce99e02f12ec96ef68360543ab1bb7c3cb81a4a2bf78df7d8597e9df-primary.xml.gzbin0 -> 966 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/filelists.xml.gzbin0 -> 773 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/other.xml.gzbin0 -> 742 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/primary.xml.gzbin0 -> 1459 bytes
-rw-r--r--spec/functional/assets/yumrepo/repodata/repomd.xml72
-rw-r--r--spec/functional/audit/rspec_formatter_spec.rb2
-rw-r--r--spec/functional/audit/runner_spec.rb2
-rw-r--r--spec/functional/dsl/reboot_pending_spec.rb6
-rw-r--r--spec/functional/dsl/registry_helper_spec.rb6
-rw-r--r--spec/functional/event_loggers/windows_eventlog_spec.rb4
-rw-r--r--spec/functional/http/simple_spec.rb24
-rw-r--r--spec/functional/knife/exec_spec.rb2
-rw-r--r--spec/functional/knife/ssh_spec.rb65
-rw-r--r--spec/functional/mixin/from_file_spec.rb82
-rw-r--r--spec/functional/mixin/powershell_out_spec.rb26
-rw-r--r--spec/functional/mixin/shell_out_spec.rb36
-rw-r--r--spec/functional/notifications_spec.rb2
-rw-r--r--spec/functional/rebooter_spec.rb41
-rwxr-xr-xspec/functional/resource/aixinit_service_spec.rb4
-rw-r--r--spec/functional/resource/apt_package_spec.rb (renamed from spec/functional/resource/package_spec.rb)42
-rw-r--r--spec/functional/resource/bash_spec.rb2
-rw-r--r--spec/functional/resource/bff_spec.rb8
-rw-r--r--spec/functional/resource/cron_spec.rb2
-rw-r--r--spec/functional/resource/deploy_revision_spec.rb881
-rw-r--r--spec/functional/resource/dnf_package_spec.rb244
-rw-r--r--spec/functional/resource/dsc_script_spec.rb188
-rwxr-xr-xspec/functional/resource/env_spec.rb192
-rw-r--r--spec/functional/resource/execute_spec.rb12
-rw-r--r--spec/functional/resource/file_spec.rb2
-rw-r--r--spec/functional/resource/git_spec.rb38
-rw-r--r--spec/functional/resource/group_spec.rb2
-rw-r--r--spec/functional/resource/ifconfig_spec.rb15
-rw-r--r--spec/functional/resource/link_spec.rb24
-rw-r--r--spec/functional/resource/mount_spec.rb14
-rw-r--r--spec/functional/resource/powershell_script_spec.rb28
-rw-r--r--spec/functional/resource/reboot_spec.rb6
-rw-r--r--spec/functional/resource/registry_spec.rb170
-rw-r--r--spec/functional/resource/remote_file_spec.rb34
-rw-r--r--spec/functional/resource/rpm_spec.rb2
-rw-r--r--spec/functional/resource/template_spec.rb10
-rw-r--r--spec/functional/resource/user/dscl_spec.rb6
-rw-r--r--spec/functional/resource/user/useradd_spec.rb709
-rw-r--r--spec/functional/resource/user/windows_spec.rb4
-rw-r--r--spec/functional/resource/windows_env_spec.rb285
-rw-r--r--spec/functional/resource/windows_service_spec.rb2
-rw-r--r--spec/functional/resource/windows_task_spec.rb1345
-rw-r--r--spec/functional/resource/yum_package_spec.rb957
-rw-r--r--spec/functional/root_alias_spec.rb2
-rw-r--r--spec/functional/run_lock_spec.rb8
-rw-r--r--spec/functional/shell_spec.rb2
-rw-r--r--spec/functional/util/powershell/cmdlet_spec.rb14
-rw-r--r--spec/functional/version_spec.rb2
-rw-r--r--spec/functional/win32/crypto_spec.rb18
-rw-r--r--spec/functional/win32/registry_spec.rb132
-rw-r--r--spec/functional/win32/security_spec.rb123
-rw-r--r--spec/functional/win32/versions_spec.rb16
-rw-r--r--spec/integration/client/client_spec.rb502
-rw-r--r--spec/integration/client/exit_code_spec.rb38
-rw-r--r--spec/integration/client/ipv6_spec.rb74
-rw-r--r--spec/integration/knife/chef_fs_data_store_spec.rb260
-rw-r--r--spec/integration/knife/chef_repo_path_spec.rb836
-rw-r--r--spec/integration/knife/chef_repository_file_system_spec.rb70
-rw-r--r--spec/integration/knife/chefignore_spec.rb176
-rw-r--r--spec/integration/knife/client_bulk_delete_spec.rb98
-rw-r--r--spec/integration/knife/client_create_spec.rb10
-rw-r--r--spec/integration/knife/client_delete_spec.rb26
-rw-r--r--spec/integration/knife/client_key_delete_spec.rb4
-rw-r--r--spec/integration/knife/client_key_list_spec.rb8
-rw-r--r--spec/integration/knife/client_list_spec.rb16
-rw-r--r--spec/integration/knife/common_options_spec.rb62
-rw-r--r--spec/integration/knife/config_get_profile_spec.rb112
-rw-r--r--spec/integration/knife/config_get_spec.rb183
-rw-r--r--spec/integration/knife/config_list_profiles_spec.rb188
-rw-r--r--spec/integration/knife/config_use_profile_spec.rb100
-rw-r--r--spec/integration/knife/cookbook_api_ipv6_spec.rb76
-rw-r--r--spec/integration/knife/cookbook_bulk_delete_spec.rb28
-rw-r--r--spec/integration/knife/cookbook_download_spec.rb24
-rw-r--r--spec/integration/knife/cookbook_list_spec.rb16
-rw-r--r--spec/integration/knife/cookbook_show_spec.rb162
-rw-r--r--spec/integration/knife/cookbook_upload_spec.rb48
-rw-r--r--spec/integration/knife/data_bag_delete_spec.rb16
-rw-r--r--spec/integration/knife/data_bag_from_file_spec.rb94
-rw-r--r--spec/integration/knife/data_bag_list_spec.rb8
-rw-r--r--spec/integration/knife/data_bag_show_spec.rb14
-rw-r--r--spec/integration/knife/delete_spec.rb1186
-rw-r--r--spec/integration/knife/deps_spec.rb374
-rw-r--r--spec/integration/knife/diff_spec.rb232
-rw-r--r--spec/integration/knife/download_spec.rb1020
-rw-r--r--spec/integration/knife/environment_compare_spec.rb30
-rw-r--r--spec/integration/knife/environment_from_file_spec.rb118
-rw-r--r--spec/integration/knife/environment_list_spec.rb8
-rw-r--r--spec/integration/knife/environment_show_spec.rb50
-rw-r--r--spec/integration/knife/list_spec.rb1462
-rw-r--r--spec/integration/knife/node_bulk_delete_spec.rb16
-rw-r--r--spec/integration/knife/node_delete_spec.rb12
-rw-r--r--spec/integration/knife/node_environment_set_spec.rb6
-rw-r--r--spec/integration/knife/node_from_file_spec.rb32
-rw-r--r--spec/integration/knife/node_list_spec.rb10
-rw-r--r--spec/integration/knife/raw_spec.rb234
-rw-r--r--spec/integration/knife/role_bulk_delete_spec.rb16
-rw-r--r--spec/integration/knife/role_delete_spec.rb12
-rw-r--r--spec/integration/knife/role_from_file_spec.rb84
-rw-r--r--spec/integration/knife/role_list_spec.rb10
-rw-r--r--spec/integration/knife/role_show_spec.rb18
-rw-r--r--spec/integration/knife/show_spec.rb114
-rw-r--r--spec/integration/knife/upload_spec.rb792
-rw-r--r--spec/integration/recipes/accumulator_spec.rb4
-rw-r--r--spec/integration/recipes/lwrp_inline_resources_spec.rb16
-rw-r--r--spec/integration/recipes/lwrp_spec.rb24
-rw-r--r--spec/integration/recipes/noop_resource_spec.rb2
-rw-r--r--spec/integration/recipes/notifies_spec.rb334
-rw-r--r--spec/integration/recipes/notifying_block_spec.rb4
-rw-r--r--spec/integration/recipes/recipe_dsl_spec.rb112
-rw-r--r--spec/integration/recipes/remote_directory.rb2
-rw-r--r--spec/integration/recipes/resource_action_spec.rb147
-rw-r--r--spec/integration/recipes/resource_converge_if_changed_spec.rb232
-rw-r--r--spec/integration/recipes/resource_load_spec.rb16
-rw-r--r--spec/integration/solo/solo_spec.rb84
-rw-r--r--spec/scripts/ssl-serve.rb24
-rw-r--r--spec/spec_helper.rb176
-rw-r--r--spec/stress/win32/file_spec.rb4
-rw-r--r--spec/stress/win32/security_spec.rb4
-rw-r--r--spec/support/lib/chef/resource/one_two_three_four.rb2
-rw-r--r--spec/support/lib/chef/resource/zen_master.rb4
-rw-r--r--spec/support/mock/constant.rb2
-rw-r--r--spec/support/platform_helpers.rb30
-rw-r--r--spec/support/shared/context/client.rb71
-rw-r--r--spec/support/shared/examples/client.rb51
-rw-r--r--spec/support/shared/functional/execute_resource.rb2
-rw-r--r--spec/support/shared/functional/file_resource.rb2
-rw-r--r--spec/support/shared/functional/securable_resource.rb32
-rw-r--r--spec/support/shared/functional/securable_resource_with_reporting.rb12
-rw-r--r--spec/support/shared/functional/win32_service.rb10
-rw-r--r--spec/support/shared/functional/windows_script.rb6
-rw-r--r--spec/support/shared/integration/app_server_support.rb6
-rw-r--r--spec/support/shared/integration/integration_helper.rb4
-rw-r--r--spec/support/shared/integration/knife_support.rb17
-rw-r--r--spec/support/shared/unit/api_error_inspector.rb12
-rw-r--r--spec/support/shared/unit/api_versioning.rb4
-rw-r--r--spec/support/shared/unit/application_dot_d.rb2
-rw-r--r--spec/support/shared/unit/execute_resource.rb15
-rw-r--r--spec/support/shared/unit/provider/file.rb34
-rw-r--r--spec/support/shared/unit/provider/useradd_based_user_provider.rb74
-rw-r--r--spec/support/shared/unit/user_and_client_shared.rb6
-rw-r--r--spec/tiny_server.rb16
-rw-r--r--spec/unit/api_client/registration_spec.rb60
-rw-r--r--spec/unit/api_client_spec.rb12
-rw-r--r--spec/unit/api_client_v1_spec.rb12
-rw-r--r--spec/unit/application/apply_spec.rb8
-rw-r--r--spec/unit/application/client_spec.rb75
-rw-r--r--spec/unit/application/knife_spec.rb6
-rw-r--r--spec/unit/application/solo_spec.rb19
-rw-r--r--spec/unit/application_spec.rb89
-rw-r--r--spec/unit/audit/audit_event_proxy_spec.rb96
-rw-r--r--spec/unit/audit/audit_reporter_spec.rb138
-rw-r--r--spec/unit/audit/control_group_data_spec.rb40
-rw-r--r--spec/unit/audit/runner_spec.rb4
-rw-r--r--spec/unit/chef_class_spec.rb120
-rw-r--r--spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb82
-rw-r--r--spec/unit/chef_fs/data_handler/data_handler_base_spec.rb65
-rw-r--r--spec/unit/chef_fs/diff_spec.rb90
-rw-r--r--spec/unit/chef_fs/file_pattern_spec.rb4
-rw-r--r--spec/unit/chef_fs/file_system/repository/directory_spec.rb8
-rw-r--r--spec/unit/chef_fs/file_system_spec.rb18
-rw-r--r--spec/unit/chef_fs/parallelizer.rb24
-rw-r--r--spec/unit/client_spec.rb50
-rw-r--r--spec/unit/config_fetcher_spec.rb46
-rw-r--r--spec/unit/config_spec.rb4
-rw-r--r--spec/unit/cookbook/gem_installer_spec.rb9
-rw-r--r--spec/unit/cookbook/manifest_v0_spec.rb2
-rw-r--r--spec/unit/cookbook/metadata_spec.rb164
-rw-r--r--spec/unit/cookbook/synchronizer_spec.rb334
-rw-r--r--spec/unit/cookbook_loader_spec.rb27
-rw-r--r--spec/unit/cookbook_manifest_spec.rb6
-rw-r--r--spec/unit/cookbook_site_streaming_uploader_spec.rb12
-rw-r--r--spec/unit/cookbook_uploader_spec.rb16
-rw-r--r--spec/unit/cookbook_version_file_specificity_spec.rb270
-rw-r--r--spec/unit/daemon_spec.rb41
-rw-r--r--spec/unit/data_bag_item_spec.rb6
-rw-r--r--spec/unit/data_bag_spec.rb2
-rw-r--r--spec/unit/data_collector/messages/helpers_spec.rb9
-rw-r--r--spec/unit/data_collector/resource_report_spec.rb8
-rw-r--r--spec/unit/data_collector_spec.rb139
-rw-r--r--spec/unit/deprecated_spec.rb32
-rw-r--r--spec/unit/dsl/audit_spec.rb2
-rw-r--r--spec/unit/dsl/declare_resource_spec.rb11
-rw-r--r--spec/unit/dsl/platform_introspection_spec.rb32
-rw-r--r--spec/unit/dsl/reboot_pending_spec.rb15
-rw-r--r--spec/unit/dsl/recipe_spec.rb19
-rw-r--r--spec/unit/environment_spec.rb36
-rw-r--r--spec/unit/exceptions_spec.rb2
-rw-r--r--spec/unit/file_access_control_spec.rb16
-rw-r--r--spec/unit/file_content_management/deploy/mv_unix_spec.rb6
-rw-r--r--spec/unit/file_content_management/deploy/mv_windows_spec.rb52
-rw-r--r--spec/unit/formatters/base_spec.rb39
-rw-r--r--spec/unit/formatters/error_description_spec.rb78
-rw-r--r--spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb32
-rw-r--r--spec/unit/formatters/error_inspectors/cookbook_sync_error_inspector_spec.rb2
-rw-r--r--spec/unit/formatters/error_inspectors/node_load_error_inspector_spec.rb2
-rw-r--r--spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb2
-rw-r--r--spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb2
-rw-r--r--spec/unit/formatters/error_inspectors/run_list_expansion_error_inspector_spec.rb10
-rw-r--r--spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb8
-rw-r--r--spec/unit/handler/json_file_spec.rb2
-rw-r--r--spec/unit/http/api_versions_spec.rb2
-rw-r--r--spec/unit/http/authenticator_spec.rb55
-rw-r--r--spec/unit/http/http_request_spec.rb8
-rw-r--r--spec/unit/http/ssl_policies_spec.rb2
-rw-r--r--spec/unit/http/validate_content_length_spec.rb14
-rw-r--r--spec/unit/http_spec.rb9
-rw-r--r--spec/unit/key_spec.rb24
-rw-r--r--spec/unit/knife/bootstrap/client_builder_spec.rb6
-rw-r--r--spec/unit/knife/bootstrap_spec.rb31
-rw-r--r--spec/unit/knife/client_bulk_delete_spec.rb2
-rw-r--r--spec/unit/knife/client_delete_spec.rb2
-rw-r--r--spec/unit/knife/client_reregister_spec.rb2
-rw-r--r--spec/unit/knife/configure_client_spec.rb8
-rw-r--r--spec/unit/knife/configure_spec.rb75
-rw-r--r--spec/unit/knife/cookbook_bulk_delete_spec.rb2
-rw-r--r--spec/unit/knife/cookbook_delete_spec.rb8
-rw-r--r--spec/unit/knife/cookbook_download_spec.rb42
-rw-r--r--spec/unit/knife/cookbook_list_spec.rb14
-rw-r--r--spec/unit/knife/cookbook_show_spec.rb48
-rw-r--r--spec/unit/knife/cookbook_test_spec.rb4
-rw-r--r--spec/unit/knife/cookbook_upload_spec.rb38
-rw-r--r--spec/unit/knife/core/bootstrap_context_spec.rb74
-rw-r--r--spec/unit/knife/core/cookbook_scm_repo_spec.rb40
-rw-r--r--spec/unit/knife/core/gem_glob_loader_spec.rb4
-rw-r--r--spec/unit/knife/core/hashed_command_loader_spec.rb2
-rw-r--r--spec/unit/knife/core/node_editor_spec.rb12
-rw-r--r--spec/unit/knife/core/object_loader_spec.rb2
-rw-r--r--spec/unit/knife/core/ui_spec.rb110
-rw-r--r--spec/unit/knife/data_bag_create_spec.rb52
-rw-r--r--spec/unit/knife/data_bag_edit_spec.rb2
-rw-r--r--spec/unit/knife/data_bag_secret_options_spec.rb10
-rw-r--r--spec/unit/knife/data_bag_show_spec.rb18
-rw-r--r--spec/unit/knife/environment_compare_spec.rb6
-rw-r--r--spec/unit/knife/environment_from_file_spec.rb2
-rw-r--r--spec/unit/knife/index_rebuild_spec.rb125
-rw-r--r--spec/unit/knife/key_create_spec.rb8
-rw-r--r--spec/unit/knife/key_delete_spec.rb6
-rw-r--r--spec/unit/knife/key_edit_spec.rb6
-rw-r--r--spec/unit/knife/key_list_spec.rb6
-rw-r--r--spec/unit/knife/key_show_spec.rb6
-rw-r--r--spec/unit/knife/knife_help.rb92
-rw-r--r--spec/unit/knife/node_delete_spec.rb2
-rw-r--r--spec/unit/knife/node_edit_spec.rb18
-rw-r--r--spec/unit/knife/node_from_file_spec.rb2
-rw-r--r--spec/unit/knife/node_policy_set_spec.rb122
-rw-r--r--spec/unit/knife/node_run_list_add_spec.rb2
-rw-r--r--spec/unit/knife/osc_user_edit_spec.rb2
-rw-r--r--spec/unit/knife/osc_user_reregister_spec.rb4
-rw-r--r--spec/unit/knife/osc_user_show_spec.rb2
-rw-r--r--spec/unit/knife/role_bulk_delete_spec.rb2
-rw-r--r--spec/unit/knife/role_create_spec.rb2
-rw-r--r--spec/unit/knife/role_delete_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_add_spec.rb8
-rw-r--r--spec/unit/knife/role_env_run_list_clear_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_remove_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_replace_spec.rb2
-rw-r--r--spec/unit/knife/role_env_run_list_set_spec.rb2
-rw-r--r--spec/unit/knife/role_from_file_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_add_spec.rb8
-rw-r--r--spec/unit/knife/role_run_list_clear_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_remove_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_replace_spec.rb2
-rw-r--r--spec/unit/knife/role_run_list_set_spec.rb2
-rw-r--r--spec/unit/knife/ssh_spec.rb198
-rw-r--r--spec/unit/knife/ssl_check_spec.rb46
-rw-r--r--spec/unit/knife/ssl_fetch_spec.rb22
-rw-r--r--spec/unit/knife/supermarket_download_spec.rb (renamed from spec/unit/knife/cookbook_site_download_spec.rb)54
-rw-r--r--spec/unit/knife/supermarket_install_spec.rb (renamed from spec/unit/knife/cookbook_site_install_spec.rb)19
-rw-r--r--spec/unit/knife/supermarket_share_spec.rb (renamed from spec/unit/knife/cookbook_site_share_spec.rb)28
-rw-r--r--spec/unit/knife/supermarket_unshare_spec.rb (renamed from spec/unit/knife/cookbook_site_unshare_spec.rb)11
-rw-r--r--spec/unit/knife/user_delete_spec.rb2
-rw-r--r--spec/unit/knife/user_reregister_spec.rb2
-rw-r--r--spec/unit/knife_spec.rb54
-rw-r--r--spec/unit/log/syslog_spec.rb8
-rw-r--r--spec/unit/log/winevt_spec.rb5
-rw-r--r--spec/unit/lwrp_spec.rb24
-rw-r--r--spec/unit/mash_spec.rb6
-rw-r--r--spec/unit/mixin/api_version_request_handling_spec.rb32
-rw-r--r--spec/unit/mixin/checksum_spec.rb2
-rw-r--r--spec/unit/mixin/enforce_ownership_and_permissions_spec.rb16
-rw-r--r--spec/unit/mixin/homebrew_user_spec.rb8
-rw-r--r--spec/unit/mixin/openssl_helper_spec.rb252
-rw-r--r--spec/unit/mixin/params_validate_spec.rb197
-rw-r--r--spec/unit/mixin/powershell_exec_spec.rb43
-rw-r--r--spec/unit/mixin/powershell_type_coercions_spec.rb15
-rw-r--r--spec/unit/mixin/properties_spec.rb14
-rw-r--r--spec/unit/mixin/securable_spec.rb54
-rw-r--r--spec/unit/mixin/shell_out_spec.rb438
-rw-r--r--spec/unit/mixin/user_context_spec.rb5
-rw-r--r--spec/unit/mixin/xml_escape_spec.rb2
-rw-r--r--spec/unit/node/attribute_spec.rb26
-rw-r--r--spec/unit/node/immutable_collections_spec.rb12
-rw-r--r--spec/unit/node/vivid_mash_spec.rb6
-rw-r--r--spec/unit/node_map_spec.rb129
-rw-r--r--spec/unit/node_spec.rb63
-rw-r--r--spec/unit/org_spec.rb4
-rw-r--r--spec/unit/platform/query_helpers_spec.rb65
-rw-r--r--spec/unit/policy_builder/expand_node_object_spec.rb8
-rw-r--r--spec/unit/policy_builder/policyfile_spec.rb139
-rw-r--r--spec/unit/property/validation_spec.rb64
-rw-r--r--spec/unit/property_spec.rb60
-rw-r--r--spec/unit/provider/apt_repository_spec.rb169
-rw-r--r--spec/unit/provider/apt_update_spec.rb16
-rw-r--r--spec/unit/provider/cookbook_file/content_spec.rb2
-rw-r--r--spec/unit/provider/cookbook_file_spec.rb3
-rw-r--r--spec/unit/provider/cron/unix_spec.rb35
-rw-r--r--spec/unit/provider/cron_spec.rb617
-rw-r--r--spec/unit/provider/deploy/revision_spec.rb110
-rw-r--r--spec/unit/provider/deploy/timestamped_spec.rb40
-rw-r--r--spec/unit/provider/deploy_spec.rb641
-rw-r--r--spec/unit/provider/dsc_resource_spec.rb12
-rw-r--r--spec/unit/provider/env/windows_spec.rb103
-rw-r--r--spec/unit/provider/erl_call_spec.rb77
-rw-r--r--spec/unit/provider/execute_spec.rb35
-rw-r--r--spec/unit/provider/file/content_spec.rb2
-rw-r--r--spec/unit/provider/file_spec.rb3
-rw-r--r--spec/unit/provider/git_spec.rb260
-rw-r--r--spec/unit/provider/group/dscl_spec.rb66
-rw-r--r--spec/unit/provider/group/gpasswd_spec.rb21
-rw-r--r--spec/unit/provider/group/groupadd_spec.rb14
-rw-r--r--spec/unit/provider/group/groupmod_spec.rb35
-rw-r--r--spec/unit/provider/group/pw_spec.rb15
-rw-r--r--spec/unit/provider/group/suse_spec.rb4
-rw-r--r--spec/unit/provider/group/usermod_spec.rb8
-rw-r--r--spec/unit/provider/group_spec.rb6
-rw-r--r--spec/unit/provider/ifconfig/aix_spec.rb34
-rw-r--r--spec/unit/provider/ifconfig/debian_spec.rb32
-rw-r--r--spec/unit/provider/ifconfig_spec.rb37
-rw-r--r--spec/unit/provider/launchd_spec.rb104
-rw-r--r--spec/unit/provider/link_spec.rb24
-rw-r--r--spec/unit/provider/log_spec.rb31
-rw-r--r--spec/unit/provider/mdadm_spec.rb6
-rw-r--r--spec/unit/provider/mount/aix_spec.rb92
-rw-r--r--spec/unit/provider/mount/mount_spec.rb126
-rw-r--r--spec/unit/provider/mount/solaris_spec.rb176
-rw-r--r--spec/unit/provider/mount/windows_spec.rb12
-rw-r--r--spec/unit/provider/ohai_spec.rb18
-rw-r--r--spec/unit/provider/osx_profile_spec.rb10
-rw-r--r--spec/unit/provider/package/apt_spec.rb946
-rw-r--r--spec/unit/provider/package/bff_spec.rb (renamed from spec/unit/provider/package/aix_spec.rb)84
-rw-r--r--spec/unit/provider/package/cab_spec.rb116
-rw-r--r--spec/unit/provider/package/chocolatey_spec.rb83
-rw-r--r--spec/unit/provider/package/dpkg_spec.rb66
-rw-r--r--spec/unit/provider/package/freebsd/pkg_spec.rb70
-rw-r--r--spec/unit/provider/package/freebsd/pkgng_spec.rb44
-rw-r--r--spec/unit/provider/package/freebsd/port_spec.rb42
-rw-r--r--spec/unit/provider/package/homebrew_spec.rb11
-rw-r--r--spec/unit/provider/package/ips_spec.rb188
-rw-r--r--spec/unit/provider/package/macports_spec.rb46
-rw-r--r--spec/unit/provider/package/msu_spec.rb88
-rw-r--r--spec/unit/provider/package/openbsd_spec.rb38
-rw-r--r--spec/unit/provider/package/pacman_spec.rb100
-rw-r--r--spec/unit/provider/package/paludis_spec.rb66
-rw-r--r--spec/unit/provider/package/portage_spec.rb190
-rw-r--r--spec/unit/provider/package/powershell_spec.rb308
-rw-r--r--spec/unit/provider/package/rpm_spec.rb42
-rw-r--r--spec/unit/provider/package/rubygems_spec.rb160
-rw-r--r--spec/unit/provider/package/smartos_spec.rb42
-rw-r--r--spec/unit/provider/package/solaris_spec.rb76
-rw-r--r--spec/unit/provider/package/windows/exe_spec.rb2
-rw-r--r--spec/unit/provider/package/windows/msi_spec.rb2
-rw-r--r--spec/unit/provider/package/windows_spec.rb21
-rw-r--r--spec/unit/provider/package/yum/python_helper_spec.rb29
-rw-r--r--spec/unit/provider/package/yum/yum_cache_spec.rb90
-rw-r--r--spec/unit/provider/package/yum_spec.rb2294
-rw-r--r--spec/unit/provider/package/zypper_spec.rb107
-rw-r--r--spec/unit/provider/package_spec.rb71
-rw-r--r--spec/unit/provider/powershell_script_spec.rb4
-rw-r--r--spec/unit/provider/registry_key_spec.rb52
-rw-r--r--spec/unit/provider/remote_directory_spec.rb2
-rw-r--r--spec/unit/provider/remote_file/cache_control_data_spec.rb14
-rw-r--r--spec/unit/provider/remote_file/content_spec.rb8
-rw-r--r--spec/unit/provider/remote_file/fetcher_spec.rb10
-rw-r--r--spec/unit/provider/remote_file/ftp_spec.rb2
-rw-r--r--spec/unit/provider/remote_file/http_spec.rb50
-rw-r--r--spec/unit/provider/remote_file/local_file_spec.rb4
-rw-r--r--spec/unit/provider/remote_file/network_file_spec.rb8
-rw-r--r--spec/unit/provider/remote_file/sftp_spec.rb4
-rw-r--r--spec/unit/provider/remote_file_spec.rb3
-rw-r--r--spec/unit/provider/route_spec.rb2
-rw-r--r--spec/unit/provider/script_spec.rb6
-rw-r--r--spec/unit/provider/service/aix_service_spec.rb16
-rw-r--r--spec/unit/provider/service/aixinit_service_spec.rb6
-rw-r--r--spec/unit/provider/service/arch_service_spec.rb60
-rw-r--r--spec/unit/provider/service/debian_service_spec.rb204
-rw-r--r--spec/unit/provider/service/freebsd_service_spec.rb72
-rw-r--r--spec/unit/provider/service/gentoo_service_spec.rb2
-rw-r--r--spec/unit/provider/service/init_service_spec.rb50
-rw-r--r--spec/unit/provider/service/insserv_service_spec.rb4
-rw-r--r--spec/unit/provider/service/invokercd_service_spec.rb52
-rw-r--r--spec/unit/provider/service/macosx_spec.rb130
-rw-r--r--spec/unit/provider/service/openbsd_service_spec.rb24
-rw-r--r--spec/unit/provider/service/redhat_spec.rb54
-rw-r--r--spec/unit/provider/service/simple_service_spec.rb34
-rw-r--r--spec/unit/provider/service/solaris_smf_service_spec.rb39
-rw-r--r--spec/unit/provider/service/systemd_service_spec.rb60
-rw-r--r--spec/unit/provider/service/upstart_service_spec.rb32
-rw-r--r--spec/unit/provider/service/windows_spec.rb559
-rw-r--r--spec/unit/provider/service_spec.rb6
-rw-r--r--spec/unit/provider/subversion_spec.rb26
-rw-r--r--spec/unit/provider/systemd_unit_spec.rb395
-rw-r--r--spec/unit/provider/template/content_spec.rb88
-rw-r--r--spec/unit/provider/template_spec.rb8
-rw-r--r--spec/unit/provider/user/aix_spec.rb11
-rw-r--r--spec/unit/provider/user/dscl_spec.rb60
-rw-r--r--spec/unit/provider/user/pw_spec.rb24
-rw-r--r--spec/unit/provider/user/solaris_spec.rb17
-rw-r--r--spec/unit/provider/user/windows_spec.rb3
-rw-r--r--spec/unit/provider/windows_env_spec.rb (renamed from spec/unit/provider/env_spec.rb)118
-rw-r--r--spec/unit/provider/windows_task_spec.rb675
-rw-r--r--spec/unit/provider/zypper_repository_spec.rb126
-rw-r--r--spec/unit/provider_resolver_spec.rb72
-rw-r--r--spec/unit/provider_spec.rb8
-rw-r--r--spec/unit/recipe_spec.rb34
-rw-r--r--spec/unit/resource/apt_package_spec.rb20
-rw-r--r--spec/unit/resource/apt_preference_spec.rb32
-rw-r--r--spec/unit/resource/apt_repository_spec.rb74
-rw-r--r--spec/unit/resource/apt_update_spec.rb32
-rw-r--r--spec/unit/resource/bash_spec.rb23
-rw-r--r--spec/unit/resource/batch_spec.rb7
-rw-r--r--spec/unit/resource/bff_package_spec.rb51
-rw-r--r--spec/unit/resource/breakpoint_spec.rb8
-rw-r--r--spec/unit/resource/build_essential_spec.rb43
-rw-r--r--spec/unit/resource/cab_package_spec.rb34
-rw-r--r--spec/unit/resource/chef_gem_spec.rb20
-rw-r--r--spec/unit/resource/chef_handler_spec.rb40
-rw-r--r--spec/unit/resource/chocolatey_config_spec.rb98
-rw-r--r--spec/unit/resource/chocolatey_package_spec.rb36
-rw-r--r--spec/unit/resource/chocolatey_source_spec.rb102
-rw-r--r--spec/unit/resource/conditional_spec.rb12
-rw-r--r--spec/unit/resource/cookbook_file_spec.rb65
-rw-r--r--spec/unit/resource/cron_spec.rb159
-rw-r--r--spec/unit/resource/csh_spec.rb23
-rw-r--r--spec/unit/resource/deploy_spec.rb283
-rw-r--r--spec/unit/resource/directory_spec.rb57
-rw-r--r--spec/unit/resource/dmg_package_spec.rb (renamed from spec/unit/resource/deploy_revision_spec.rb)33
-rw-r--r--spec/unit/resource/dnf_package_spec.rb85
-rw-r--r--spec/unit/resource/dpkg_package_spec.rb18
-rw-r--r--spec/unit/resource/dsc_resource_spec.rb12
-rw-r--r--spec/unit/resource/dsc_script_spec.rb98
-rw-r--r--spec/unit/resource/env_spec.rb85
-rw-r--r--spec/unit/resource/erl_call_spec.rb81
-rw-r--r--spec/unit/resource/execute_spec.rb44
-rw-r--r--spec/unit/resource/file/verification/systemd_unit_spec.rb2
-rw-r--r--spec/unit/resource/file/verification_spec.rb24
-rw-r--r--spec/unit/resource/file_spec.rb115
-rw-r--r--spec/unit/resource/freebsd_package_spec.rb78
-rw-r--r--spec/unit/resource/gem_package_spec.rb35
-rw-r--r--spec/unit/resource/git_spec.rb34
-rw-r--r--spec/unit/resource/group_spec.rb134
-rw-r--r--spec/unit/resource/homebrew_cask_spec.rb40
-rw-r--r--spec/unit/resource/homebrew_package_spec.rb18
-rw-r--r--spec/unit/resource/homebrew_tap_spec.rb44
-rw-r--r--spec/unit/resource/hostname_spec.rb47
-rw-r--r--spec/unit/resource/http_request_spec.rb40
-rw-r--r--spec/unit/resource/ifconfig_spec.rb6
-rw-r--r--spec/unit/resource/ips_package_spec.rb28
-rw-r--r--spec/unit/resource/kernel_module_spec.rb48
-rw-r--r--spec/unit/resource/ksh_spec.rb23
-rw-r--r--spec/unit/resource/launchd_spec.rb38
-rw-r--r--spec/unit/resource/link_spec.rb112
-rw-r--r--spec/unit/resource/log_spec.rb53
-rw-r--r--spec/unit/resource/macos_user_defaults_spec.rb (renamed from spec/unit/resource/timestamped_deploy_spec.rb)25
-rw-r--r--spec/unit/resource/macports_package_spec.rb19
-rw-r--r--spec/unit/resource/mdadm_spec.rb85
-rw-r--r--spec/unit/resource/mount_spec.rb223
-rw-r--r--spec/unit/resource/msu_package_spec.rb36
-rw-r--r--spec/unit/resource/ohai_hint_spec.rb44
-rw-r--r--spec/unit/resource/ohai_spec.rb33
-rw-r--r--spec/unit/resource/openbsd_package_spec.rb38
-rw-r--r--spec/unit/resource/openssl_dhparam.rb56
-rw-r--r--spec/unit/resource/openssl_rsa_private_key_spec.rb64
-rw-r--r--spec/unit/resource/openssl_rsa_public_key_spec.rb43
-rw-r--r--spec/unit/resource/osx_profile_spec.rb22
-rw-r--r--spec/unit/resource/package_spec.rb81
-rw-r--r--spec/unit/resource/pacman_package_spec.rb20
-rw-r--r--spec/unit/resource/paludis_package_spec.rb36
-rw-r--r--spec/unit/resource/perl_spec.rb22
-rw-r--r--spec/unit/resource/portage_package_spec.rb28
-rw-r--r--spec/unit/resource/powershell_package_source_spec.rb219
-rw-r--r--spec/unit/resource/powershell_package_spec.rb54
-rw-r--r--spec/unit/resource/powershell_script_spec.rb16
-rw-r--r--spec/unit/resource/python_spec.rb20
-rw-r--r--spec/unit/resource/reboot_spec.rb47
-rw-r--r--spec/unit/resource/registry_key_spec.rb192
-rw-r--r--spec/unit/resource/remote_directory_spec.rb90
-rw-r--r--spec/unit/resource/remote_file_spec.rb175
-rw-r--r--spec/unit/resource/resource_notification_spec.rb16
-rw-r--r--spec/unit/resource/rhsm_errata_level_spec.rb50
-rw-r--r--spec/unit/resource/rhsm_errata_spec.rb39
-rw-r--r--spec/unit/resource/rhsm_register_spec.rb204
-rw-r--r--spec/unit/resource/rhsm_repo_spec.rb64
-rw-r--r--spec/unit/resource/rhsm_subscription_spec.rb98
-rw-r--r--spec/unit/resource/route_spec.rb84
-rw-r--r--spec/unit/resource/rpm_package_spec.rb28
-rw-r--r--spec/unit/resource/ruby_block_spec.rb33
-rw-r--r--spec/unit/resource/ruby_spec.rb19
-rw-r--r--spec/unit/resource/scm_spec.rb138
-rw-r--r--spec/unit/resource/script_spec.rb10
-rw-r--r--spec/unit/resource/service_spec.rb175
-rw-r--r--spec/unit/resource/smartos_package_spec.rb23
-rw-r--r--spec/unit/resource/solaris_package_spec.rb20
-rw-r--r--spec/unit/resource/ssh_known_hosts_entry_spec.rb55
-rw-r--r--spec/unit/resource/subversion_spec.rb58
-rw-r--r--spec/unit/resource/sudo_spec.rb99
-rw-r--r--spec/unit/resource/swap_file_spec.rb39
-rw-r--r--spec/unit/resource/sysctl_spec.rb54
-rw-r--r--spec/unit/resource/systemd_unit_spec.rb116
-rw-r--r--spec/unit/resource/template_spec.rb132
-rw-r--r--spec/unit/resource/user_spec.rb99
-rw-r--r--spec/unit/resource/windows_ad_join_spec.rb51
-rw-r--r--spec/unit/resource/windows_auto_run_spec.rb50
-rw-r--r--spec/unit/resource/windows_env_spec.rb75
-rw-r--r--spec/unit/resource/windows_feature.rb60
-rw-r--r--spec/unit/resource/windows_feature_dism.rb72
-rw-r--r--spec/unit/resource/windows_feature_powershell.rb72
-rw-r--r--spec/unit/resource/windows_font_spec.rb43
-rw-r--r--spec/unit/resource/windows_package_spec.rb20
-rw-r--r--spec/unit/resource/windows_pagefile_spec.rb49
-rw-r--r--spec/unit/resource/windows_path_spec.rb18
-rw-r--r--spec/unit/resource/windows_printer_port_spec.rb62
-rw-r--r--spec/unit/resource/windows_printer_spec.rb52
-rw-r--r--spec/unit/resource/windows_service_spec.rb54
-rw-r--r--spec/unit/resource/windows_shortcut_spec.rb38
-rw-r--r--spec/unit/resource/windows_task_spec.rb221
-rw-r--r--spec/unit/resource/yum_package_spec.rb8
-rw-r--r--spec/unit/resource/yum_repository_spec.rb121
-rw-r--r--spec/unit/resource/zypper_package_spec.rb51
-rw-r--r--spec/unit/resource/zypper_repository_spec.rb106
-rw-r--r--spec/unit/resource_collection/resource_set_spec.rb12
-rw-r--r--spec/unit/resource_collection_spec.rb10
-rw-r--r--spec/unit/resource_definition_spec.rb4
-rw-r--r--spec/unit/resource_inspector_spec.rb60
-rw-r--r--spec/unit/resource_reporter_spec.rb50
-rw-r--r--spec/unit/resource_spec.rb128
-rw-r--r--spec/unit/role_spec.rb44
-rw-r--r--spec/unit/run_context_spec.rb2
-rw-r--r--spec/unit/run_list/run_list_item_spec.rb6
-rw-r--r--spec/unit/run_list/versioned_recipe_list_spec.rb24
-rw-r--r--spec/unit/run_list_spec.rb12
-rw-r--r--spec/unit/runner_spec.rb8
-rw-r--r--spec/unit/scan_access_control_spec.rb6
-rw-r--r--spec/unit/shell/model_wrapper_spec.rb8
-rw-r--r--spec/unit/shell/shell_ext_spec.rb8
-rw-r--r--spec/unit/shell/shell_session_spec.rb57
-rw-r--r--spec/unit/user_spec.rb6
-rw-r--r--spec/unit/user_v1_spec.rb50
-rw-r--r--spec/unit/util/diff_spec.rb2
-rw-r--r--spec/unit/util/dsc/configuration_generator_spec.rb8
-rw-r--r--spec/unit/util/dsc/lcm_output_parser_spec.rb260
-rw-r--r--spec/unit/util/dsc/local_configuration_manager_spec.rb101
-rw-r--r--spec/unit/util/file_edit_spec.rb76
-rw-r--r--spec/unit/util/powershell/cmdlet_spec.rb2
-rw-r--r--spec/unit/util/selinux_spec.rb23
-rw-r--r--spec/unit/util/windows/logon_session_spec.rb3
-rw-r--r--spec/unit/win32/registry_spec.rb6
-rw-r--r--spec/unit/win32/security_spec.rb45
-rw-r--r--spec/unit/windows_service_spec.rb10
597 files changed, 23048 insertions, 19234 deletions
diff --git a/spec/data/client.d_00/02-strings.rb b/spec/data/client.d_00/02-strings.rb
new file mode 100644
index 0000000000..7d9a49268c
--- /dev/null
+++ b/spec/data/client.d_00/02-strings.rb
@@ -0,0 +1,2 @@
+# 02-strings.rb
+something '/foo/bar'
diff --git a/spec/data/mixin/invalid_data.rb b/spec/data/mixin/invalid_data.rb
new file mode 100644
index 0000000000..e6f6c3a783
--- /dev/null
+++ b/spec/data/mixin/invalid_data.rb
@@ -0,0 +1,3 @@
+# For spec/functional/mixin/from_file_spec.rb
+a :foo
+c :bar
diff --git a/spec/data/mixin/real_data.rb b/spec/data/mixin/real_data.rb
new file mode 100644
index 0000000000..e15b86fc68
--- /dev/null
+++ b/spec/data/mixin/real_data.rb
@@ -0,0 +1,2 @@
+# For spec/functional/mixin/from_file_spec.rb
+a :foo
diff --git a/spec/functional/assets/chefinittest b/spec/functional/assets/chefinittest
index 79e064cd5f..b67abbfa43 100755
--- a/spec/functional/assets/chefinittest
+++ b/spec/functional/assets/chefinittest
@@ -1,15 +1,17 @@
#!/bin/ksh
+TMPDIR="${TMPDIR:-/tmp}"
+
function create_chef_txt {
- touch /tmp/chefinittest.txt
+ touch $TMPDIR/chefinittest.txt
}
function delete_chef_txt {
- rm /tmp/chefinittest.txt
+ rm $TMPDIR/chefinittest.txt
}
function rename_chef_txt {
- mv /tmp/chefinittest.txt /tmp/$1
+ mv $TMPDIR/chefinittest.txt $TMPDIR/$1
}
case "$1" in
@@ -20,7 +22,7 @@ stop )
delete_chef_txt
;;
status )
- [ -f /tmp/chefinittest.txt ] || [ -f /tmp/chefinittest_reload.txt ] || [ -f /tmp/chefinittest_restart.txt ]
+ [ -f $TMPDIR/chefinittest.txt ] || [ -f $TMPDIR/chefinittest_reload.txt ] || [ -f $TMPDIR/chefinittest_restart.txt ]
;;
reload )
rename_chef_txt "chefinittest_reload.txt"
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.aarch64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.aarch64.rpm
new file mode 100644
index 0000000000..808e5c64c9
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.aarch64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.i686.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.i686.rpm
deleted file mode 100644
index 29a4624971..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.i686.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.src.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.src.rpm
deleted file mode 100644
index b6a6ec3176..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.src.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpm
deleted file mode 100644
index 239b6ef145..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.i686.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.i686.rpm
new file mode 100644
index 0000000000..ed7b6ddc8e
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.i686.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64.rpm
new file mode 100644
index 0000000000..f3683b3c89
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64le.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64le.rpm
new file mode 100644
index 0000000000..4f8de433d9
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.ppc64le.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.s390x.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.s390x.rpm
new file mode 100644
index 0000000000..98538293ff
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.s390x.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.src.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.src.rpm
new file mode 100644
index 0000000000..03a92f1cfc
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.src.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.10-1.x86_64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.x86_64.rpm
new file mode 100644
index 0000000000..3533640780
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.10-1.x86_64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.aarch64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.aarch64.rpm
new file mode 100644
index 0000000000..73d59bf3e2
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.aarch64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.i686.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.i686.rpm
deleted file mode 100644
index 3421c3628f..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.i686.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.src.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.src.rpm
deleted file mode 100644
index d420659fd5..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.src.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm
deleted file mode 100644
index 93c1f5e3e3..0000000000
--- a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.i686.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.i686.rpm
new file mode 100644
index 0000000000..6637756abb
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.i686.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64.rpm
new file mode 100644
index 0000000000..677e43f83b
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64le.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64le.rpm
new file mode 100644
index 0000000000..df21a68780
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.ppc64le.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.s390x.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.s390x.rpm
new file mode 100644
index 0000000000..02a771c6f5
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.s390x.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.src.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.src.rpm
new file mode 100644
index 0000000000..5d4d13e18a
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.src.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/chef_rpm-1.2-1.x86_64.rpm b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.x86_64.rpm
new file mode 100644
index 0000000000..314c52f22e
--- /dev/null
+++ b/spec/functional/assets/yumrepo/chef_rpm-1.2-1.x86_64.rpm
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0-primary.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0-primary.sqlite.bz2
deleted file mode 100644
index d7726b9df6..0000000000
--- a/spec/functional/assets/yumrepo/repodata/313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0-primary.sqlite.bz2
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553-other.xml.gz b/spec/functional/assets/yumrepo/repodata/31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553-other.xml.gz
deleted file mode 100644
index 30d7778ac4..0000000000
--- a/spec/functional/assets/yumrepo/repodata/31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553-other.xml.gz
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/4632d67cb92636e7575d911c24f0e04d3505a944e97c483abe0c3e73a7c62d33-filelists.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/4632d67cb92636e7575d911c24f0e04d3505a944e97c483abe0c3e73a7c62d33-filelists.sqlite.bz2
new file mode 100644
index 0000000000..3c5e406935
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/4632d67cb92636e7575d911c24f0e04d3505a944e97c483abe0c3e73a7c62d33-filelists.sqlite.bz2
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773-filelists.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773-filelists.sqlite.bz2
deleted file mode 100644
index 2df608aa34..0000000000
--- a/spec/functional/assets/yumrepo/repodata/4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773-filelists.sqlite.bz2
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243-primary.xml.gz b/spec/functional/assets/yumrepo/repodata/66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243-primary.xml.gz
deleted file mode 100644
index d9b7cb879a..0000000000
--- a/spec/functional/assets/yumrepo/repodata/66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243-primary.xml.gz
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/74599b793e54d877323837d2d81a1c3c594c44e4335f9528234bb490f7b9b439-other.xml.gz b/spec/functional/assets/yumrepo/repodata/74599b793e54d877323837d2d81a1c3c594c44e4335f9528234bb490f7b9b439-other.xml.gz
new file mode 100644
index 0000000000..ddccd353ae
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/74599b793e54d877323837d2d81a1c3c594c44e4335f9528234bb490f7b9b439-other.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16-filelists.xml.gz b/spec/functional/assets/yumrepo/repodata/8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16-filelists.xml.gz
deleted file mode 100644
index 35a973d170..0000000000
--- a/spec/functional/assets/yumrepo/repodata/8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16-filelists.xml.gz
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/a845d418f919d2115ab95a56b2c76f6825ad0d0bede49181a55c04f58995d057-primary.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/a845d418f919d2115ab95a56b2c76f6825ad0d0bede49181a55c04f58995d057-primary.sqlite.bz2
new file mode 100644
index 0000000000..50bbe1f37f
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/a845d418f919d2115ab95a56b2c76f6825ad0d0bede49181a55c04f58995d057-primary.sqlite.bz2
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/af9b7cf9ef23bd7b43068d74a460f3b5d06753d638e58e4a0c9edc35bfb9cdc4-other.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/af9b7cf9ef23bd7b43068d74a460f3b5d06753d638e58e4a0c9edc35bfb9cdc4-other.sqlite.bz2
new file mode 100644
index 0000000000..e341e1df69
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/af9b7cf9ef23bd7b43068d74a460f3b5d06753d638e58e4a0c9edc35bfb9cdc4-other.sqlite.bz2
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc-other.sqlite.bz2 b/spec/functional/assets/yumrepo/repodata/b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc-other.sqlite.bz2
deleted file mode 100644
index e682fc0f0b..0000000000
--- a/spec/functional/assets/yumrepo/repodata/b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc-other.sqlite.bz2
+++ /dev/null
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/bdb4f5f1492a3b9532f22c43110a81500dd744f23da0aec5c33b2a41317c737d-filelists.xml.gz b/spec/functional/assets/yumrepo/repodata/bdb4f5f1492a3b9532f22c43110a81500dd744f23da0aec5c33b2a41317c737d-filelists.xml.gz
new file mode 100644
index 0000000000..9636d5b868
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/bdb4f5f1492a3b9532f22c43110a81500dd744f23da0aec5c33b2a41317c737d-filelists.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/c10d1d34ce99e02f12ec96ef68360543ab1bb7c3cb81a4a2bf78df7d8597e9df-primary.xml.gz b/spec/functional/assets/yumrepo/repodata/c10d1d34ce99e02f12ec96ef68360543ab1bb7c3cb81a4a2bf78df7d8597e9df-primary.xml.gz
new file mode 100644
index 0000000000..afa4b4db9a
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/c10d1d34ce99e02f12ec96ef68360543ab1bb7c3cb81a4a2bf78df7d8597e9df-primary.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/filelists.xml.gz b/spec/functional/assets/yumrepo/repodata/filelists.xml.gz
new file mode 100644
index 0000000000..954b9abcd7
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/filelists.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/other.xml.gz b/spec/functional/assets/yumrepo/repodata/other.xml.gz
new file mode 100644
index 0000000000..db6ffa611d
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/other.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/primary.xml.gz b/spec/functional/assets/yumrepo/repodata/primary.xml.gz
new file mode 100644
index 0000000000..fe06057d60
--- /dev/null
+++ b/spec/functional/assets/yumrepo/repodata/primary.xml.gz
Binary files differ
diff --git a/spec/functional/assets/yumrepo/repodata/repomd.xml b/spec/functional/assets/yumrepo/repodata/repomd.xml
index 92937e151a..31be5c80f5 100644
--- a/spec/functional/assets/yumrepo/repodata/repomd.xml
+++ b/spec/functional/assets/yumrepo/repodata/repomd.xml
@@ -1,55 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
-<repomd xmlns="http://linux.duke.edu/metadata/repo" xmlns:rpm="http://linux.duke.edu/metadata/rpm">
- <revision>1479418959</revision>
-<data type="filelists">
- <checksum type="sha256">8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16</checksum>
- <open-checksum type="sha256">9f5be999b4a535c19afc53703851577e1a325227fab651189c5c39708b9a1e38</open-checksum>
- <location href="repodata/8b34697595fcc87928e12d24644dda9462c3857bd932861e28bc77ae1f31be16-filelists.xml.gz"/>
- <timestamp>1479418959</timestamp>
- <size>419</size>
- <open-size>1127</open-size>
-</data>
-<data type="primary">
- <checksum type="sha256">66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243</checksum>
- <open-checksum type="sha256">dc25cfbf4520861130e0ba203d27cc40b183fbb7c576aac33d838fb20a68aa32</open-checksum>
- <location href="repodata/66391e53f0510b98b3f0b79f40ba1048026d9a1ef20905d9c40ba6f5411f3243-primary.xml.gz"/>
- <timestamp>1479418959</timestamp>
- <size>859</size>
- <open-size>4529</open-size>
-</data>
-<data type="primary_db">
- <checksum type="sha256">313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0</checksum>
- <open-checksum type="sha256">720b637c782cce8604b922e9989ecfff9091e26163d643bd1b676778beb1c933</open-checksum>
- <location href="repodata/313329137b55fd333b2dc66394a6661a2befa6cc535d8460d92a4a78a9c581f0-primary.sqlite.bz2"/>
- <timestamp>1479418959</timestamp>
- <database_version>10</database_version>
- <size>2460</size>
- <open-size>32768</open-size>
-</data>
-<data type="other_db">
- <checksum type="sha256">b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc</checksum>
- <open-checksum type="sha256">938156bcfc95828cb6857e1b2790dceaef57196843a80464ba5749772fc15e83</open-checksum>
- <location href="repodata/b97cca3fe14bcf06c52be4449b6108f7731239ff221111dcce8aada5467f60dc-other.sqlite.bz2"/>
- <timestamp>1479418959</timestamp>
- <database_version>10</database_version>
- <size>967</size>
- <open-size>6144</open-size>
-</data>
-<data type="other">
- <checksum type="sha256">31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553</checksum>
- <open-checksum type="sha256">2ea64cdb2f5ba3859af29fe67a85d61d5b4de23f3da1ee71d5af175d8d887ab6</open-checksum>
- <location href="repodata/31ac4db5d5ac593728fcc26aef82b7b93c4cc4dbec843786b1845b939b658553-other.xml.gz"/>
- <timestamp>1479418959</timestamp>
- <size>413</size>
- <open-size>1035</open-size>
-</data>
-<data type="filelists_db">
- <checksum type="sha256">4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773</checksum>
- <open-checksum type="sha256">8bc15efa19d02a5112e20c6ed1be17c5851287ddfba17aee2283ddb216dd08d7</open-checksum>
- <location href="repodata/4ac40fa3c6728c1401318e2e20a997436624e83dcf7a5f952b851ef422637773-filelists.sqlite.bz2"/>
- <timestamp>1479418959</timestamp>
- <database_version>10</database_version>
- <size>1131</size>
- <open-size>7168</open-size>
-</data>
+<repomd xmlns="http://linux.duke.edu/metadata/repo">
+ <data type="other">
+ <location href="repodata/other.xml.gz"/>
+ <checksum type="sha">6d44b25ecb901d242a28a6a457d9c6a240e93a72</checksum>
+ <timestamp>1512520884</timestamp>
+ <open-checksum type="sha">f3e463916922801d1be801e28304c84b2ee58638</open-checksum>
+ </data>
+ <data type="filelists">
+ <location href="repodata/filelists.xml.gz"/>
+ <checksum type="sha">21dcce9b122a907aa94ec7ec6108006c0f26e7c8</checksum>
+ <timestamp>1512520884</timestamp>
+ <open-checksum type="sha">9241f39704584bd27bfc0cf7b5e8aaa21945deb9</open-checksum>
+ </data>
+ <data type="primary">
+ <location href="repodata/primary.xml.gz"/>
+ <checksum type="sha">6896c706000889416d769616f32e381db3a46ef2</checksum>
+ <timestamp>1512520884</timestamp>
+ <open-checksum type="sha">976e163091ffd175e2bad28d6b3564495ec4b1e9</open-checksum>
+ </data>
</repomd>
diff --git a/spec/functional/audit/rspec_formatter_spec.rb b/spec/functional/audit/rspec_formatter_spec.rb
index 209694ae70..f30f7bbd8a 100644
--- a/spec/functional/audit/rspec_formatter_spec.rb
+++ b/spec/functional/audit/rspec_formatter_spec.rb
@@ -30,7 +30,7 @@ describe Chef::Audit::RspecFormatter do
let(:events) { double("events").as_null_object }
let(:audits) { {} }
- let(:run_context) { instance_double(Chef::RunContext, :events => events, :audits => audits) }
+ let(:run_context) { instance_double(Chef::RunContext, events: events, audits: audits) }
let(:runner) { Chef::Audit::Runner.new(run_context) }
let(:output) { double("output") }
diff --git a/spec/functional/audit/runner_spec.rb b/spec/functional/audit/runner_spec.rb
index 54f014e28f..f80256fa5c 100644
--- a/spec/functional/audit/runner_spec.rb
+++ b/spec/functional/audit/runner_spec.rb
@@ -49,7 +49,7 @@ describe Chef::Audit::Runner do
describe "#run" do
let(:audits) { {} }
- let(:run_context) { instance_double(Chef::RunContext, :events => events, :audits => audits) }
+ let(:run_context) { instance_double(Chef::RunContext, events: events, audits: audits) }
let(:control_group_name) { "control_group_name" }
# Set cookbook path to include our parent, so that it will recognize this
diff --git a/spec/functional/dsl/reboot_pending_spec.rb b/spec/functional/dsl/reboot_pending_spec.rb
index c7a93c6822..ff7fd574b1 100644
--- a/spec/functional/dsl/reboot_pending_spec.rb
+++ b/spec/functional/dsl/reboot_pending_spec.rb
@@ -42,19 +42,19 @@ describe Chef::DSL::RebootPending, :windows_only do
describe 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations' do
let(:reg_key) { 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager' }
- let(:original_set) { registry.value_exists?(reg_key, { :name => "PendingFileRenameOperations" }) }
+ let(:original_set) { registry.value_exists?(reg_key, { name: "PendingFileRenameOperations" }) }
it "returns true if the registry value exists" do
skip "found existing registry key" if original_set
registry.set_value(reg_key,
- { :name => "PendingFileRenameOperations", :type => :multi_string, :data => ['\??\C:\foo.txt|\??\C:\bar.txt'] })
+ { name: "PendingFileRenameOperations", type: :multi_string, data: ['\??\C:\foo.txt|\??\C:\bar.txt'] })
expect(recipe.reboot_pending?).to be_truthy
end
after do
unless original_set
- registry.delete_value(reg_key, { :name => "PendingFileRenameOperations" })
+ registry.delete_value(reg_key, { name: "PendingFileRenameOperations" })
end
end
end
diff --git a/spec/functional/dsl/registry_helper_spec.rb b/spec/functional/dsl/registry_helper_spec.rb
index d90d5090e4..7a56ee11cf 100644
--- a/spec/functional/dsl/registry_helper_spec.rb
+++ b/spec/functional/dsl/registry_helper_spec.rb
@@ -42,7 +42,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 +52,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 019595ea8d..8a9475680d 100644
--- a/spec/functional/event_loggers/windows_eventlog_spec.rb
+++ b/spec/functional/event_loggers/windows_eventlog_spec.rb
@@ -19,12 +19,12 @@
require "spec_helper"
require "securerandom"
require "chef/event_loggers/windows_eventlog"
-if Chef::Platform.windows? && (not Chef::Platform.windows_server_2003?)
+if Chef::Platform.windows?
require "win32/eventlog"
include Win32
end
-describe Chef::EventLoggers::WindowsEventLogger, :windows_only, :not_supported_on_win2k3 do
+describe Chef::EventLoggers::WindowsEventLogger, :windows_only do
def rand
random.rand(1 << 32).to_s
end
diff --git a/spec/functional/http/simple_spec.rb b/spec/functional/http/simple_spec.rb
index 421045693a..562c037bb0 100644
--- a/spec/functional/http/simple_spec.rb
+++ b/spec/functional/http/simple_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Lamont Granquist (<lamont@chef.io>)
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,13 +24,19 @@ describe Chef::HTTP::Simple do
include ChefHTTPShared
let(:http_client) { described_class.new(source) }
- let(:http_client_disable_gzip) { described_class.new(source, { :disable_gzip => true } ) }
+ let(:http_client_disable_gzip) { described_class.new(source, { disable_gzip: true } ) }
+
+ before(:all) do
+ start_tiny_server(RequestTimeout: 1)
+ end
before(:each) do
- start_tiny_server
+ Chef::Config[:rest_timeout] = 2
+ Chef::Config[:http_retry_delay] = 0
+ Chef::Config[:http_retry_count] = 0
end
- after(:each) do
+ after(:all) do
stop_tiny_server
end
@@ -46,10 +52,10 @@ describe Chef::HTTP::Simple do
end
shared_examples_for "validates content length and throws an exception" do
- it "successfully downloads a streaming request" do
+ it "a streaming request throws a content length exception" do
expect { http_client.streaming_request(source) }.to raise_error(Chef::Exceptions::ContentLengthMismatch)
end
- it "successfully does a non-streaming GET request" do
+ it "a non-streaming GET request throws a content length exception" do
expect { http_client.get(source) }.to raise_error(Chef::Exceptions::ContentLengthMismatch)
end
end
@@ -81,11 +87,11 @@ describe Chef::HTTP::Simple do
it_behaves_like "downloading all the things"
- context "when Chef::Log.level = :debug" do
+ context "when Chef::Log.level = :trace" do
before do
- Chef::Log.level = :debug
+ Chef::Log.level = :trace
@debug_log = ""
- allow(Chef::Log).to receive(:debug) { |str| @debug_log << str }
+ allow(Chef::Log).to receive(:trace) { |str| @debug_log << str }
end
let(:source) { "http://localhost:9000" }
diff --git a/spec/functional/knife/exec_spec.rb b/spec/functional/knife/exec_spec.rb
index ac8f617a90..7cdf1c93eb 100644
--- a/spec/functional/knife/exec_spec.rb
+++ b/spec/functional/knife/exec_spec.rb
@@ -21,7 +21,7 @@ require "tiny_server"
describe Chef::Knife::Exec do
before(:each) do
- @server = TinyServer::Manager.new #(:debug => true)
+ @server = TinyServer::Manager.new # (:debug => true)
@server.start
end
diff --git a/spec/functional/knife/ssh_spec.rb b/spec/functional/knife/ssh_spec.rb
index 9d6fd3ae10..95e7b6454c 100644
--- a/spec/functional/knife/ssh_spec.rb
+++ b/spec/functional/knife/ssh_spec.rb
@@ -181,11 +181,11 @@ describe Chef::Knife::Ssh do
it "uses the ssh_attribute" do
@knife.run
- expect(@knife.get_ssh_attribute({ "knife_config" => "ec2.public_hostname" })).to eq("ec2.public_hostname")
+ expect(@knife.get_ssh_attribute({ "target" => "ec2.public_hostname" })).to eq("ec2.public_hostname")
end
end
- context "when knife[:ssh_attribute] is not provided]" do
+ context "when knife[:ssh_attribute] is not provided" do
before do
setup_knife(["*:*", "uptime"])
Chef::Config[:knife][:ssh_attribute] = nil
@@ -199,22 +199,69 @@ describe Chef::Knife::Ssh do
context "when -a ec2.public_public_hostname is provided" do
before do
- setup_knife(["-a ec2.public_hostname", "*:*", "uptime"])
+ setup_knife(["-a", "ec2.public_hostname", "*:*", "uptime"])
Chef::Config[:knife][:ssh_attribute] = nil
end
it "should use the value on the command line" do
@knife.run
- expect(@knife.config[:attribute]).to eq("ec2.public_hostname")
+ expect(@knife.config[:ssh_attribute]).to eq("ec2.public_hostname")
end
it "should override what is set in knife.rb" do
# This is the setting imported from knife.rb
Chef::Config[:knife][:ssh_attribute] = "fqdn"
# Then we run knife with the -a flag, which sets the above variable
- setup_knife(["-a ec2.public_hostname", "*:*", "uptime"])
+ setup_knife(["-a", "ec2.public_hostname", "*:*", "uptime"])
@knife.run
- expect(@knife.config[:attribute]).to eq("ec2.public_hostname")
+ expect(@knife.config[:ssh_attribute]).to eq("ec2.public_hostname")
+ end
+ end
+ end
+
+ describe "prefix" do
+ context "when knife[:prefix_attribute] is set" do
+ before do
+ setup_knife(["*:*", "uptime"])
+ Chef::Config[:knife][:prefix_attribute] = "name"
+ end
+
+ it "uses the prefix_attribute" do
+ @knife.run
+ expect(@knife.get_prefix_attribute({ "prefix" => "name" })).to eq("name")
+ end
+ end
+
+ context "when knife[:prefix_attribute] is not provided" do
+ before do
+ setup_knife(["*:*", "uptime"])
+ Chef::Config[:knife][:prefix_attribute] = nil
+ end
+
+ it "falls back to nil" do
+ @knife.run
+ expect(@knife.get_prefix_attribute({})).to eq(nil)
+ end
+ end
+
+ context "when --prefix-attribute ec2.public_public_hostname is provided" do
+ before do
+ setup_knife(["--prefix-attribute", "ec2.public_hostname", "*:*", "uptime"])
+ Chef::Config[:knife][:prefix_attribute] = nil
+ end
+
+ it "should use the value on the command line" do
+ @knife.run
+ expect(@knife.config[:prefix_attribute]).to eq("ec2.public_hostname")
+ end
+
+ it "should override what is set in knife.rb" do
+ # This is the setting imported from knife.rb
+ Chef::Config[:knife][:prefix_attribute] = "fqdn"
+ # Then we run knife with the -b flag, which sets the above variable
+ setup_knife(["--prefix-attribute", "ec2.public_hostname", "*:*", "uptime"])
+ @knife.run
+ expect(@knife.config[:prefix_attribute]).to eq("ec2.public_hostname")
end
end
end
@@ -254,7 +301,7 @@ describe Chef::Knife::Ssh do
end
it "uses the ssh_gateway_identity file" do
- expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { :keys => File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), :keys_only => true })
+ expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
@@ -268,7 +315,7 @@ describe Chef::Knife::Ssh do
end
it "uses the ssh_gateway_identity file" do
- expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { :keys => File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), :keys_only => true })
+ expect(@knife.session).to receive(:via).with("ec2.public_hostname", "user", { keys: File.expand_path("#{ENV['HOME']}/.ssh/aws-gateway.rsa").squeeze("/"), keys_only: true })
@knife.run
expect(@knife.config[:ssh_gateway_identity]).to eq("~/.ssh/aws-gateway.rsa")
end
@@ -305,7 +352,7 @@ describe Chef::Knife::Ssh do
Chef::Config[:chef_server_url] = "http://localhost:9000"
@api.post("/search/node?q=*:*&start=0&rows=1000", 200) do
- %({"total":1, "start":0, "rows":[{"data": {"fqdn":"the.fqdn", "config": "the_public_hostname", "knife_config": "the_public_hostname" }}]})
+ %({"total":1, "start":0, "rows":[{"data": {"fqdn":"the.fqdn", "target": "the_public_hostname"}}]})
end
end
diff --git a/spec/functional/mixin/from_file_spec.rb b/spec/functional/mixin/from_file_spec.rb
new file mode 100644
index 0000000000..a279f48790
--- /dev/null
+++ b/spec/functional/mixin/from_file_spec.rb
@@ -0,0 +1,82 @@
+#
+# Copyright:: Copyright 2014-2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Mixin::FromFile do
+ REAL_DATA = File.join(CHEF_SPEC_DATA, "mixin", "real_data.rb")
+ INVALID_DATA = File.join(CHEF_SPEC_DATA, "mixin", "invalid_data.rb")
+ NO_DATA = File.join(CHEF_SPEC_DATA, "mixin", "non_existant_data.rb")
+
+ class TestData
+ include Chef::Mixin::FromFile
+
+ def a(a = nil)
+ @a = a if a
+ @a
+ end
+ end
+
+ class ClassTestData
+ class <<self
+ include Chef::Mixin::FromFile
+
+ def a(a = nil)
+ @a = a if a
+ @a
+ end
+ end
+ end
+
+ describe "from_file" do
+ it "should load data" do
+ datum = TestData.new
+ datum.from_file(REAL_DATA)
+ expect(datum.a).to eq(:foo)
+ end
+
+ it "should load class data" do
+ datum = ClassTestData
+ datum.class_from_file(REAL_DATA)
+ expect(datum.a).to eq(:foo)
+ end
+
+ it "should set source_file" do
+ datum = TestData.new
+ datum.from_file(REAL_DATA)
+ expect(datum.source_file).to eq(REAL_DATA)
+ end
+
+ it "should set class source_file" do
+ datum = ClassTestData
+ datum.class_from_file(REAL_DATA)
+ expect(datum.source_file).to eq(REAL_DATA)
+ end
+
+ it "should fail on invalid data" do
+ datum = TestData.new
+ expect do
+ datum.from_file(INVALID_DATA)
+ end.to raise_error(NoMethodError)
+ end
+
+ it "should fail on nonexistant data" do
+ datum = TestData.new
+ expect { datum.from_file(NO_DATA) }.to raise_error(IOError)
+ end
+ end
+end
diff --git a/spec/functional/mixin/powershell_out_spec.rb b/spec/functional/mixin/powershell_out_spec.rb
index 7fc8dc5957..d6fba5b084 100644
--- a/spec/functional/mixin/powershell_out_spec.rb
+++ b/spec/functional/mixin/powershell_out_spec.rb
@@ -1,5 +1,5 @@
#
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,16 +22,8 @@ describe Chef::Mixin::PowershellOut, windows_only: true do
include Chef::Mixin::PowershellOut
describe "#powershell_out" do
- context "for windows version less than 10", windows_lt_10: true do
- it "runs a powershell command and collects stdout" do
- expect(powershell_out("get-process").run_command.stdout).to match /Handles\s+NPM\(K\)\s+PM\(K\)\s+WS\(K\)\s+VM\(M\)\s+CPU\(s\)\s+Id\s+/
- end
- end
-
- context "for windows version greater than 10", windows_gte_10: true do
- it "runs a powershell command and collects stdout" do
- expect(powershell_out("get-process").run_command.stdout).to match /Handles\s+NPM\(K\)\s+PM\(K\)\s+WS\(K\)\s+CPU\(s\)\s+Id\s+SI\s+ProcessName\s+/
- end
+ it "runs a powershell command and collects stdout" do
+ expect(powershell_out("get-process").run_command.stdout).to match /Handles/
end
it "does not raise exceptions when the command is invalid" do
@@ -40,16 +32,8 @@ describe Chef::Mixin::PowershellOut, windows_only: true do
end
describe "#powershell_out!" do
- context "for windows version less than 10", windows_lt_10: true do
- it "runs a powershell command and collects stdout" do
- expect(powershell_out!("get-process").run_command.stdout).to match /Handles\s+NPM\(K\)\s+PM\(K\)\s+WS\(K\)\s+VM\(M\)\s+CPU\(s\)\s+Id\s+/
- end
- end
-
- context "for windows version less than 10", windows_gte_10: true do
- it "runs a powershell command and collects stdout" do
- expect(powershell_out("get-process").run_command.stdout).to match /Handles\s+NPM\(K\)\s+PM\(K\)\s+WS\(K\)\s+CPU\(s\)\s+Id\s+SI\s+ProcessName\s+/
- end
+ it "runs a powershell command and collects stdout" do
+ expect(powershell_out!("get-process").run_command.stdout).to match /Handles/
end
it "raises exceptions when the command is invalid" do
diff --git a/spec/functional/mixin/shell_out_spec.rb b/spec/functional/mixin/shell_out_spec.rb
index 48f6b7d912..b3e9bf796d 100644
--- a/spec/functional/mixin/shell_out_spec.rb
+++ b/spec/functional/mixin/shell_out_spec.rb
@@ -1,5 +1,5 @@
#
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,6 +21,10 @@ describe Chef::Mixin::ShellOut do
include Chef::Mixin::ShellOut
describe "shell_out_with_systems_locale" do
+ before do
+ Chef::Config[:treat_deprecation_warnings_as_errors] = false
+ end
+
describe "when environment['LC_ALL'] is not set" do
it "should use the default shell_out setting" do
cmd = if windows?
@@ -36,9 +40,35 @@ 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" })
+ end
+
+ expect(cmd.stdout.chomp).to eq "POSIX"
+ end
+ end
+ end
+
+ describe "shell_out default_env: false" do
+ describe "when environment['LC_ALL'] is not set" do
+ it "should use the default shell_out setting" do
+ cmd = if windows?
+ shell_out("echo %LC_ALL%", default_env: false)
+ else
+ shell_out("echo $LC_ALL", default_env: false)
+ end
+
+ expect(cmd.stdout.chomp).to match_environment_variable("LC_ALL")
+ end
+ end
+
+ describe "when environment['LC_ALL'] is set" do
+ it "should use the option's setting" do
+ cmd = if windows?
+ shell_out("echo %LC_ALL%", environment: { "LC_ALL" => "POSIX" }, default_env: false)
else
- shell_out_with_systems_locale("echo $LC_ALL", :environment => { "LC_ALL" => "POSIX" })
+ shell_out("echo $LC_ALL", environment: { "LC_ALL" => "POSIX" }, default_env: false)
end
expect(cmd.stdout.chomp).to eq "POSIX"
diff --git a/spec/functional/notifications_spec.rb b/spec/functional/notifications_spec.rb
index 8d8b2d970c..87afbd8359 100644
--- a/spec/functional/notifications_spec.rb
+++ b/spec/functional/notifications_spec.rb
@@ -26,7 +26,7 @@ describe "Notifications" do
before do
# By default, every provider will do nothing
- p = Chef::Provider.new(nil, run_context)
+ p = Chef::Provider.new(Chef::Resource.new("lies"), run_context)
allow_any_instance_of(Chef::Resource).to receive(:provider_for_action).and_return(p)
allow(p).to receive(:run_action)
end
diff --git a/spec/functional/rebooter_spec.rb b/spec/functional/rebooter_spec.rb
index a28491cc0b..8e5b23f86b 100644
--- a/spec/functional/rebooter_spec.rb
+++ b/spec/functional/rebooter_spec.rb
@@ -22,9 +22,9 @@ describe Chef::Platform::Rebooter do
let(:reboot_info) do
{
- :delay_mins => 5,
- :requested_by => "reboot resource functional test",
- :reason => "rebooter spec test",
+ delay_mins: 5,
+ requested_by: "reboot resource functional test",
+ reason: "rebooter spec test",
}
end
@@ -35,16 +35,18 @@ describe Chef::Platform::Rebooter do
resource
end
+ let(:node) { Chef::Node.new }
+
let(:run_context) do
- node = Chef::Node.new
events = Chef::EventDispatch::Dispatcher.new
Chef::RunContext.new(node, {}, events)
end
let(:expected) do
{
- :windows => "#{ENV['SYSTEMROOT']}/System32/shutdown.exe /r /t 300 /c \"rebooter spec test\"",
- :linux => 'shutdown -r +5 "rebooter spec test"',
+ windows: "#{ENV['SYSTEMROOT']}/System32/shutdown.exe /r /t 300 /c \"rebooter spec test\"",
+ linux: 'shutdown -r +5 "rebooter spec test" &',
+ solaris: 'shutdown -i6 -g5 -y "rebooter spec test" &',
}
end
@@ -69,8 +71,9 @@ describe Chef::Platform::Rebooter do
end
shared_context "test a reboot method" do
- def test_rebooter_method(method_sym, is_windows, expected_reboot_str)
+ def test_rebooter_method(method_sym, is_windows, is_solaris, expected_reboot_str)
allow(ChefConfig).to receive(:windows?).and_return(is_windows)
+ node.automatic["os"] = node.automatic["platform"] = node.automatic["platform_family"] = "solaris2" if is_solaris
expect(rebooter).to receive(:shell_out!).once.with(expected_reboot_str)
expect(rebooter).to receive(:raise).with(Chef::Exceptions::Reboot)
expect(rebooter).to receive(method_sym).once.and_call_original
@@ -81,24 +84,32 @@ describe Chef::Platform::Rebooter do
describe "when using #reboot_if_needed!" do
include_context "test a reboot method"
- it "should produce the correct string on Windows", :windows_only do
- test_rebooter_method(:reboot_if_needed!, true, expected[:windows])
+ it "should produce the correct string on Windows" do
+ test_rebooter_method(:reboot_if_needed!, true, false, expected[:windows])
+ end
+
+ it "should produce a SysV-like shutdown on solaris" do
+ test_rebooter_method(:reboot_if_needed!, false, true, expected[:solaris])
end
- it "should produce the correct (Linux-specific) string on non-Windows" do
- test_rebooter_method(:reboot_if_needed!, false, expected[:linux])
+ it "should produce a BSD-like shutdown by default" do
+ test_rebooter_method(:reboot_if_needed!, false, false, expected[:linux])
end
end
describe "when using #reboot!" do
include_context "test a reboot method"
- it "should produce the correct string on Windows", :windows_only do
- test_rebooter_method(:reboot!, true, expected[:windows])
+ it "should produce the correct string on Windows" do
+ test_rebooter_method(:reboot!, true, false, expected[:windows])
+ end
+
+ it "should produce a SysV-like shutdown on solaris" do
+ test_rebooter_method(:reboot!, false, true, expected[:solaris])
end
- it "should produce the correct (Linux-specific) string on non-Windows" do
- test_rebooter_method(:reboot!, false, expected[:linux])
+ it "should produce a BSD-like shutdown by default" do
+ test_rebooter_method(:reboot!, false, false, expected[:linux])
end
end
end
diff --git a/spec/functional/resource/aixinit_service_spec.rb b/spec/functional/resource/aixinit_service_spec.rb
index bf50046b03..68ea5ab8b2 100755
--- a/spec/functional/resource/aixinit_service_spec.rb
+++ b/spec/functional/resource/aixinit_service_spec.rb
@@ -59,7 +59,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 +70,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")).to_s, "/etc/rc.d/init.d/chefinittest")
end
after(:all) do
diff --git a/spec/functional/resource/package_spec.rb b/spec/functional/resource/apt_package_spec.rb
index 0f01a751ec..c1ac51c4b1 100644
--- a/spec/functional/resource/package_spec.rb
+++ b/spec/functional/resource/apt_package_spec.rb
@@ -1,7 +1,7 @@
# encoding: UTF-8
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2013-2016, Chef Software, Inc.
+# Copyright:: Copyright 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,7 +23,7 @@ require "webrick"
module AptServer
def enable_testing_apt_source
File.open("/etc/apt/sources.list.d/chef-integration-test.list", "w+") do |f|
- f.puts "deb http://localhost:9000/ sid main"
+ f.puts "deb [trusted=yes] http://localhost:9000/ sid main"
end
# Magic to update apt cache for only our repo
shell_out!("apt-get update " +
@@ -50,11 +50,11 @@ module AptServer
def apt_server
@apt_server ||= WEBrick::HTTPServer.new(
- :Port => 9000,
- :DocumentRoot => apt_data_dir + "/var/www/apt",
+ Port: 9000,
+ DocumentRoot: apt_data_dir + "/var/www/apt",
# Make WEBrick quiet, comment out for debug.
- :Logger => Logger.new(StringIO.new),
- :AccessLog => [ StringIO.new, WEBrick::AccessLog::COMMON_LOG_FORMAT ]
+ Logger: Logger.new(StringIO.new),
+ AccessLog: [ StringIO.new, WEBrick::AccessLog::COMMON_LOG_FORMAT ]
)
end
@@ -86,13 +86,13 @@ module AptServer
end
end
-metadata = { :unix_only => true,
- :requires_root => true,
- :provider => { :package => Chef::Provider::Package::Apt },
- :arch => "x86_64" # test packages are 64bit
+metadata = { unix_only: true,
+ requires_root: true,
+ provider: { package: Chef::Provider::Package::Apt },
+ arch: "x86_64" # test packages are 64bit
}
-describe Chef::Resource::Package, metadata do
+describe Chef::Resource::AptPackage, metadata do
include Chef::Mixin::ShellOut
context "with a remote package source" do
@@ -143,7 +143,7 @@ describe Chef::Resource::Package, metadata do
end
def base_resource
- r = Chef::Resource::Package.new("chef-integration-test", run_context)
+ r = Chef::Resource::AptPackage.new("chef-integration-test", run_context)
# The apt repository in the spec data is not gpg signed, so we need to
# force apt to accept the package:
r.options("--force-yes")
@@ -169,13 +169,13 @@ describe Chef::Resource::Package, metadata do
it "does nothing for action :remove" do
package_resource.run_action(:remove)
- shell_out!("dpkg -l chef-integration-test", :returns => [1])
+ shell_out!("dpkg -l chef-integration-test", returns: [1])
expect(package_resource).not_to be_updated_by_last_action
end
it "does nothing for action :purge" do
package_resource.run_action(:purge)
- shell_out!("dpkg -l chef-integration-test", :returns => [1])
+ shell_out!("dpkg -l chef-integration-test", returns: [1])
expect(package_resource).not_to be_updated_by_last_action
end
@@ -275,7 +275,7 @@ describe Chef::Resource::Package, metadata do
r = base_resource
r.cookbook_name = "preseed"
r.response_file("preseed-template-variables.seed")
- r.response_file_variables({ :template_variable => "SUPPORTS VARIABLES" })
+ r.response_file_variables({ template_variable: "SUPPORTS VARIABLES" })
r
end
@@ -300,13 +300,13 @@ describe Chef::Resource::Package, metadata do
it "does nothing for action :install" do
package_resource.run_action(:install)
- shell_out!("dpkg -l chef-integration-test", :returns => [0])
+ shell_out!("dpkg -l chef-integration-test", returns: [0])
expect(package_resource).not_to be_updated_by_last_action
end
it "does nothing for action :upgrade" do
package_resource.run_action(:upgrade)
- shell_out!("dpkg -l chef-integration-test", :returns => [0])
+ shell_out!("dpkg -l chef-integration-test", returns: [0])
expect(package_resource).not_to be_updated_by_last_action
end
@@ -324,7 +324,7 @@ describe Chef::Resource::Package, metadata do
# un chef-integration-test <none> (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/)
@@ -353,13 +353,13 @@ describe Chef::Resource::Package, metadata do
it "does nothing for action :install" do
package_resource.run_action(:install)
- shell_out!("dpkg -l chef-integration-test", :returns => [0])
+ shell_out!("dpkg -l chef-integration-test", returns: [0])
expect(package_resource).not_to be_updated_by_last_action
end
it "upgrades the package for action :upgrade" do
package_resource.run_action(:upgrade)
- dpkg_l = shell_out!("dpkg -l chef-integration-test", :returns => [0])
+ dpkg_l = shell_out!("dpkg -l chef-integration-test", returns: [0])
expect(dpkg_l.stdout).to match(/chef\-integration\-test[\s]+1\.1\-1/)
expect(package_resource).to be_updated_by_last_action
end
@@ -373,7 +373,7 @@ describe Chef::Resource::Package, metadata do
it "upgrades the package for action :install" do
package_resource.run_action(:install)
- dpkg_l = shell_out!("dpkg -l chef-integration-test", :returns => [0])
+ dpkg_l = shell_out!("dpkg -l chef-integration-test", returns: [0])
expect(dpkg_l.stdout).to match(/chef\-integration\-test[\s]+1\.1\-1/)
expect(package_resource).to be_updated_by_last_action
end
diff --git a/spec/functional/resource/bash_spec.rb b/spec/functional/resource/bash_spec.rb
index 4a5fee64bc..969ed8f605 100644
--- a/spec/functional/resource/bash_spec.rb
+++ b/spec/functional/resource/bash_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Resource::Bash, :unix_only do
resource
end
- describe "when setting the command attribute" do
+ describe "when setting the command property" do
let (:command) { "wizard racket" }
it "should raise an exception when trying to set the command" do
diff --git a/spec/functional/resource/bff_spec.rb b/spec/functional/resource/bff_spec.rb
index e7f7540e5a..9943e821e9 100644
--- a/spec/functional/resource/bff_spec.rb
+++ b/spec/functional/resource/bff_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Prabhu Das (<prabhu.das@clogeny.com>)
-# Copyright:: Copyright 2013-2016, Chef Software Inc.
+# Copyright:: Copyright 2013-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,7 +20,7 @@ require "functional/resource/base"
require "chef/mixin/shell_out"
# Run the test only for AIX platform.
-describe Chef::Resource::BffPackage, :requires_root, :external => ohai[:platform] != "aix" do
+describe Chef::Resource::BffPackage, :requires_root, external: ohai[:platform] != "aix" do
include Chef::Mixin::ShellOut
let(:new_resource) do
@@ -62,7 +62,7 @@ describe Chef::Resource::BffPackage, :requires_root, :external => ohai[:platform
context "package install action with options" do
it "should install a package" do
- new_resource.options("-e/tmp/installp.log")
+ new_resource.options("-e#{Dir.tmpdir}/installp.log")
new_resource.run_action(:install)
bff_pkg_should_be_installed(new_resource)
end
@@ -108,7 +108,7 @@ describe Chef::Resource::BffPackage, :requires_root, :external => ohai[:platform
end
it "should remove an installed package" do
- new_resource.options("-e/tmp/installp.log")
+ new_resource.options("-e#{Dir.tmpdir}/installp.log")
new_resource.run_action(:remove)
bff_pkg_should_be_removed(new_resource)
end
diff --git a/spec/functional/resource/cron_spec.rb b/spec/functional/resource/cron_spec.rb
index 1bff8bf874..84fe304585 100644
--- a/spec/functional/resource/cron_spec.rb
+++ b/spec/functional/resource/cron_spec.rb
@@ -105,7 +105,7 @@ describe Chef::Resource::Cron, :requires_root, :unix_only do
end
exclude_solaris = %w{solaris opensolaris solaris2 omnios}.include?(ohai[:platform])
- describe "create action with various attributes", :external => exclude_solaris 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./)
diff --git a/spec/functional/resource/deploy_revision_spec.rb b/spec/functional/resource/deploy_revision_spec.rb
deleted file mode 100644
index 572609d8ff..0000000000
--- a/spec/functional/resource/deploy_revision_spec.rb
+++ /dev/null
@@ -1,881 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2012-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-require "tmpdir"
-
-# Deploy relies heavily on symlinks, so it doesn't work on windows.
-describe Chef::Resource::DeployRevision, :unix_only => true, :requires_git => true do
-
- let(:file_cache_path) { Dir.mktmpdir }
- let(:deploy_directory) { Dir.mktmpdir }
-
- # By making restart or other operations write to this file, we can externally
- # track the order in which those operations happened.
- let(:observe_order_file) { Tempfile.new("deploy-resource-observe-operations") }
-
- before do
- Chef::Log.level = :info
- @old_file_cache_path = Chef::Config[:file_cache_path]
- Chef::Config[:file_cache_path] = file_cache_path
- end
-
- after do
- Chef::Config[:file_cache_path] = @old_file_cache_path
- FileUtils.remove_entry_secure deploy_directory if File.exist?(deploy_directory)
- FileUtils.remove_entry_secure file_cache_path
- observe_order_file.close
- FileUtils.remove_entry_secure observe_order_file.path
- end
-
- before(:all) do
- @ohai = Ohai::System.new
- @ohai.all_plugins(%w{platform os})
- end
-
- let(:node) do
- Chef::Node.new.tap do |n|
- n.name "rspec-test"
- n.consume_external_attrs(@ohai.data, {})
- end
- end
-
- let(:event_dispatch) { Chef::EventDispatch::Dispatcher.new }
- let(:run_context) { Chef::RunContext.new(node, {}, event_dispatch) }
-
- # These tests use git's bundle feature, which is a way to export an entire
- # git repo (or subset of commits) as a single file.
- #
- # Generally you can treat a git bundle as a regular git remote.
- #
- # See also: http://git-scm.com/2010/03/10/bundles.html
- let(:git_bundle_repo) { File.expand_path("git_bundles/sinatra-test-app.gitbundle", CHEF_SPEC_DATA) }
-
- let(:git_bundle_with_in_repo_callbacks) { File.expand_path("git_bundles/sinatra-test-app-with-callback-files.gitbundle", CHEF_SPEC_DATA) }
-
- let(:git_bundle_with_in_repo_symlinks) { File.expand_path("git_bundles/sinatra-test-app-with-symlinks.gitbundle", CHEF_SPEC_DATA) }
-
- # This is the fourth version
- let(:latest_rev) { "3eb5ca6c353c83d9179dd3b29347539829b401f3" }
-
- # This is the third version
- let(:previous_rev) { "6d19a6dbecc8e37f5b2277345885c0c783eb8fb1" }
-
- # This is the second version
- let(:second_rev) { "0827e1b0e5043608ac0a824da5c558e252154ad0" }
-
- # This is the sixth version, it is on the "with-deploy-scripts" branch
- let(:rev_with_in_repo_callbacks) { "2404d015882659754bdb93ad6e4b4d3d02691a82" }
-
- # This is the fifth version in the "with-symlinks" branch
- let(:rev_with_in_repo_symlinks) { "5a4748c52aaea8250b4346a9b8ede95ee3755e28" }
-
- # Read values from the +observe_order_file+ and split each line. This way you
- # can see in which order things really happened.
- def actual_operations_order
- IO.read(observe_order_file.path).split("\n").map(&:strip)
- end
-
- # 1. touch `restart.txt` in cwd so we know that the command is run with the
- # right cwd.
- # 2. Append +tag+ to the `observe_order_file` so we can check the order in
- # which operations happen later in the test.
- def shell_restart_command(tag)
- "touch restart.txt && echo '#{tag}' >> #{observe_order_file.path}"
- end
-
- let(:basic_deploy_resource) do
- Chef::Resource::DeployRevision.new(deploy_directory, run_context).tap do |r|
- r.name "deploy-revision-unit-test"
- r.repo git_bundle_repo
- r.symlink_before_migrate({})
- r.symlinks({})
- end
- end
-
- let(:deploy_to_latest_rev) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(latest_rev)
- r.restart_command shell_restart_command(:deploy_to_latest_rev)
- end
- end
-
- let(:deploy_to_previous_rev) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(previous_rev)
- r.restart_command shell_restart_command(:deploy_to_previous_rev)
- end
- end
-
- let(:deploy_to_latest_rev_again) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(latest_rev)
- r.restart_command shell_restart_command(:deploy_to_latest_rev_again)
- end
- end
-
- let(:deploy_to_previous_rev_again) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(previous_rev)
- r.restart_command shell_restart_command(:deploy_to_previous_rev_again)
- end
- end
-
- let(:deploy_to_second_rev) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(second_rev)
- r.restart_command shell_restart_command(:deploy_to_second_rev)
- end
- end
-
- let(:deploy_to_second_rev_again) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(second_rev)
- r.restart_command shell_restart_command(:deploy_to_second_rev_again)
- end
- end
-
- let(:deploy_to_second_rev_again_again) do
- basic_deploy_resource.dup.tap do |r|
- r.revision(second_rev)
- r.restart_command shell_restart_command(:deploy_to_second_rev_again_again)
- end
- end
-
- # Computes the full path for +path+ relative to the deploy directory
- def rel_path(path)
- File.expand_path(path, deploy_directory)
- end
-
- def actual_current_rev
- Dir.chdir(rel_path("current")) do
- `git rev-parse HEAD`.strip
- end
- end
-
- def self.the_app_is_deployed_at_revision(target_rev_spec)
- it "deploys the app to the target revision (#{target_rev_spec})" do
- target_rev = send(target_rev_spec)
-
- expect(File).to exist(rel_path("current"))
-
- expect(actual_current_rev).to eq(target_rev)
-
- # Is the app code actually there?
- expect(File).to exist(rel_path("current/app/app.rb"))
- end
- end
-
- context "when deploying a simple app" do
- describe "for the first time, with the required directory layout precreated" do
- before do
- FileUtils.mkdir_p(rel_path("releases"))
- FileUtils.mkdir_p(rel_path("shared"))
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the application" do
- expect(File).to exist(rel_path("current/restart.txt"))
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev})
- end
-
- it "is marked as updated" do
- expect(deploy_to_latest_rev).to be_updated_by_last_action
- end
- end
-
- describe "back to a previously deployed revision, with the directory structure precreated" do
- before do
- FileUtils.mkdir_p(rel_path("releases"))
- FileUtils.mkdir_p(rel_path("shared"))
-
- deploy_to_latest_rev.run_action(:deploy)
- deploy_to_previous_rev.run_action(:deploy)
- deploy_to_latest_rev_again.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_latest_rev_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the fourth version of the app")
- end
- end
-
- describe "for the first time, with no existing directory layout" do
- before do
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- it "creates the required directory tree" do
- expect(File).to be_directory(rel_path("releases"))
- expect(File).to be_directory(rel_path("shared"))
- expect(File).to be_directory(rel_path("releases/#{latest_rev}"))
-
- expect(File).to be_directory(rel_path("current/tmp"))
- expect(File).to be_directory(rel_path("current/config"))
- expect(File).to be_directory(rel_path("current/public"))
-
- expect(File).to be_symlink(rel_path("current"))
- expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}"))
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the application" do
- expect(File).to exist(rel_path("current/restart.txt"))
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev})
- end
-
- it "is marked as updated" do
- expect(deploy_to_latest_rev).to be_updated_by_last_action
- end
- end
-
- describe "again to the current revision" do
- before do
- deploy_to_latest_rev.run_action(:deploy)
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "does not restart the app" do
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev})
- end
-
- 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
- before do
- deploy_to_latest_rev.run_action(:force_deploy)
- deploy_to_latest_rev_again.run_action(:force_deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the app" do
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev deploy_to_latest_rev_again})
- end
-
- 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
- before do
- deploy_to_previous_rev.run_action(:deploy)
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the application after the new deploy" do
- expect(actual_operations_order).to eq(%w{deploy_to_previous_rev deploy_to_latest_rev})
- end
-
- it "is marked updated" do
- expect(deploy_to_previous_rev).to be_updated_by_last_action
- end
-
- 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
- before do
- deploy_to_latest_rev.run_action(:deploy)
- deploy_to_previous_rev.run_action(:deploy)
- deploy_to_latest_rev_again.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_latest_rev deploy_to_previous_rev deploy_to_latest_rev_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_latest_rev_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the fourth version of the app")
- end
- end
-
- describe "back to a previously deployed revision where resource rev == latest revision (explicit rollback)" do
- before do
- deploy_to_previous_rev.run_action(:deploy)
- @previous_rev_all_releases = deploy_to_previous_rev.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev.run_action(:deploy)
- @latest_rev_all_releases = deploy_to_latest_rev.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev_again.run_action(:rollback)
- @previous_rev_again_all_releases = deploy_to_latest_rev_again.provider_for_action(:deploy).all_releases
- end
-
- the_app_is_deployed_at_revision(:previous_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_previous_rev deploy_to_latest_rev deploy_to_latest_rev_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_latest_rev_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the third version of the app")
- end
-
- it "all_releases after first deploy should have one entry" do
- expect(@previous_rev_all_releases.length).to eq(1)
- end
-
- it "all_releases after second deploy should have two entries" do
- expect(@latest_rev_all_releases.length).to eq(2)
- end
-
- it "all_releases after rollback should have one entry" do
- expect(@previous_rev_again_all_releases.length).to eq(1)
- end
-
- 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
- before do
- deploy_to_previous_rev.run_action(:deploy)
- @previous_rev_all_releases = deploy_to_previous_rev.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev.run_action(:deploy)
- @latest_rev_all_releases = deploy_to_latest_rev.provider_for_action(:deploy).all_releases
- deploy_to_previous_rev_again.run_action(:rollback)
- # FIXME: only difference with previous test is using latest_rev_again insetad of previous_rev_again
- @previous_rev_again_all_releases = deploy_to_latest_rev_again.provider_for_action(:deploy).all_releases
- end
-
- the_app_is_deployed_at_revision(:previous_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_previous_rev deploy_to_latest_rev deploy_to_previous_rev_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_previous_rev_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the third version of the app")
- end
-
- it "all_releases after first deploy should have one entry" do
- expect(@previous_rev_all_releases.length).to eq(1)
- end
-
- it "all_releases after second deploy should have two entries" do
- expect(@latest_rev_all_releases.length).to eq(2)
- end
-
- it "all_releases after rollback should have one entry" do
- expect(@previous_rev_again_all_releases.length).to eq(1)
- end
-
- 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 == latest revision (explicit rollback)" do
- before do
- deploy_to_second_rev.run_action(:deploy)
- @first_deploy_all_releases = deploy_to_second_rev.provider_for_action(:deploy).all_releases
- deploy_to_previous_rev.run_action(:deploy)
- @second_deploy_all_releases = deploy_to_previous_rev.provider_for_action(:deploy).all_releases
- deploy_to_previous_rev_again.run_action(:rollback)
- @third_deploy_all_releases = deploy_to_previous_rev_again.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev.run_action(:deploy)
- @fourth_deploy_all_releases = deploy_to_latest_rev.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev_again.run_action(:rollback)
- @fifth_deploy_all_releases = deploy_to_latest_rev_again.provider_for_action(:deploy).all_releases
- end
-
- the_app_is_deployed_at_revision(:second_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_second_rev deploy_to_previous_rev deploy_to_previous_rev_again deploy_to_latest_rev deploy_to_latest_rev_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_latest_rev_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the second version of the app")
- end
-
- it "all_releases after rollback should have one entry" do
- expect(@fifth_deploy_all_releases.length).to eq(1)
- end
-
- 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
-
- describe "back to a previously deployed revision where resource rev == latest revision (explicit rollback)" do
- before do
- deploy_to_second_rev.run_action(:deploy)
- @first_deploy_all_releases = deploy_to_second_rev.provider_for_action(:deploy).all_releases
- deploy_to_previous_rev.run_action(:deploy)
- @second_deploy_all_releases = deploy_to_previous_rev.provider_for_action(:deploy).all_releases
- deploy_to_second_rev_again.run_action(:rollback)
- @third_deploy_all_releases = deploy_to_second_rev_again.provider_for_action(:deploy).all_releases
- deploy_to_latest_rev.run_action(:deploy)
- @fourth_deploy_all_releases = deploy_to_latest_rev.provider_for_action(:deploy).all_releases
- deploy_to_second_rev_again_again.run_action(:rollback)
- @fifth_deploy_all_releases = deploy_to_second_rev_again_again.provider_for_action(:deploy).all_releases
- end
-
- the_app_is_deployed_at_revision(:second_rev)
-
- it "restarts the application after rolling back" do
- expect(actual_operations_order).to eq(%w{deploy_to_second_rev deploy_to_previous_rev deploy_to_second_rev_again deploy_to_latest_rev deploy_to_second_rev_again_again})
- end
-
- it "is marked updated" do
- expect(deploy_to_second_rev_again_again).to be_updated_by_last_action
- end
-
- it "deploys the right code" do
- expect(IO.read(rel_path("current/app/app.rb"))).to include("this is the second version of the app")
- end
-
- it "all_releases after rollback should have one entry" do
- expect(@fifth_deploy_all_releases.length).to eq(1)
- end
-
- 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
- # directories deeper
- let(:deploy_directory) { File.expand_path("nested/deeper", top_level_tmpdir) }
-
- after do
- FileUtils.remove_entry_secure top_level_tmpdir
- end
-
- before do
- expect(File).not_to exist(deploy_directory)
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- it "creates the required directory tree" do
- expect(File).to be_directory(rel_path("releases"))
- expect(File).to be_directory(rel_path("shared"))
- expect(File).to be_directory(rel_path("releases/#{latest_rev}"))
-
- expect(File).to be_directory(rel_path("current/tmp"))
- expect(File).to be_directory(rel_path("current/config"))
- expect(File).to be_directory(rel_path("current/public"))
-
- expect(File).to be_symlink(rel_path("current"))
- expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}"))
- 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 = []
-
- let(:deploy_to_latest_with_inline_recipes) do
- deploy_to_latest_rev.dup.tap do |r|
- r.symlink_before_migrate "config/config.ru" => "config.ru"
- r.before_migrate do
- callback_order << :before_migrate
-
- file "#{release_path}/before_migrate.txt" do
- # The content here isn't relevant, but it gets printed when running
- # the tests. Could be handy for debugging.
- content callback_order.inspect
- end
- end
- r.before_symlink do
- callback_order << :before_symlink
-
- current_release_path = release_path
- ruby_block "ensure before symlink" do
- block do
- if ::File.exist?(::File.join(current_release_path, "/tmp"))
- raise "Ordering issue with provider, expected symlinks to not have been created"
- end
- end
- end
-
- file "#{release_path}/before_symlink.txt" do
- content callback_order.inspect
- end
- end
- r.before_restart do
- callback_order << :before_restart
-
- current_release_path = release_path
- ruby_block "ensure after symlink" do
- block do
- unless ::File.exist?(::File.join(current_release_path, "/tmp"))
- raise "Ordering issue with provider, expected symlinks to have been created"
- end
- end
- end
-
- file "#{release_path}/tmp/before_restart.txt" do
- content callback_order.inspect
- end
- end
- r.after_restart do
- callback_order << :after_restart
- file "#{release_path}/tmp/after_restart.txt" do
- content callback_order.inspect
- end
- end
- end
- end
-
- before do
- callback_order.clear # callback_order variable is global for this context group
- deploy_to_latest_with_inline_recipes.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:latest_rev)
-
- it "is marked updated" do
- expect(deploy_to_latest_with_inline_recipes).to be_updated_by_last_action
- end
-
- it "calls the callbacks in order" do
- expect(callback_order).to eq([:before_migrate, :before_symlink, :before_restart, :after_restart])
- end
-
- it "runs chef resources in the callbacks" do
- expect(File).to exist(rel_path("current/before_migrate.txt"))
- expect(File).to exist(rel_path("current/before_symlink.txt"))
- 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 in-repo callback scripts" do
- let(:deploy_with_in_repo_callbacks) do
- basic_deploy_resource.dup.tap do |r|
- r.repo git_bundle_with_in_repo_callbacks
- r.revision rev_with_in_repo_callbacks
- end
- end
-
- before do
- deploy_with_in_repo_callbacks.run_action(:deploy)
- end
-
- the_app_is_deployed_at_revision(:rev_with_in_repo_callbacks)
-
- it "runs chef resources in the callbacks" do
- expect(File).to exist(rel_path("current/before_migrate.txt"))
- expect(File).to exist(rel_path("current/before_symlink.txt"))
- 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
-
- r.revision latest_rev
-
- # enable migrations
- r.migrate true
- # abuse `shell_restart_command` so we can observe order of when the
- # 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
- execute spec_context.shell_restart_command("before_migrate") do
- cwd current_release
- end
- end
- r.before_symlink do
- current_release = release_path
- execute spec_context.shell_restart_command("before_symlink") do
- cwd current_release
- end
- end
-
- r.before_restart do
- current_release = release_path
- execute spec_context.shell_restart_command("before_restart") do
- cwd current_release
- end
- end
-
- r.after_restart do
- current_release = release_path
- execute spec_context.shell_restart_command("after_restart") do
- cwd current_release
- end
- end
-
- end
- end
-
- before do
- deploy_with_migration.run_action(:deploy)
- end
-
- it "runs migrations in between the before_migrate and before_symlink steps" do
- expect(actual_operations_order).to eq(%w{before_migrate migration before_symlink before_restart after_restart})
- end
- end
-
- context "when deploying an app with in-repo symlinks" do
- let(:deploy_with_in_repo_symlinks) do
- basic_deploy_resource.dup.tap do |r|
- r.repo git_bundle_with_in_repo_symlinks
- r.revision rev_with_in_repo_symlinks
- end
- end
-
- it "should not raise an exception calling File.utime on symlinks" do
- expect { deploy_with_in_repo_symlinks.run_action(:deploy) }.not_to raise_error
- end
- 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"))
- expect(File).to be_directory(rel_path("releases/#{latest_rev}"))
-
- expect(File).to be_directory(rel_path("current/tmp"))
- expect(File).to be_directory(rel_path("current/config"))
- expect(File).to be_directory(rel_path("current/public"))
-
- expect(File).to be_symlink(rel_path("current"))
- expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}"))
- end
- end
-
- # background: If a deployment is hosed and the user decides to rm -rf the
- # 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)
- deploy_to_latest_rev.dup.run_action(:deploy)
- 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"))
- deploy_to_latest_rev.dup.run_action(:deploy)
- 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"))
- expect(File).to be_directory(rel_path("releases/#{latest_rev}"))
-
- expect(File).to be_directory(rel_path("current/tmp"))
- expect(File).to be_directory(rel_path("current/config"))
- expect(File).to be_directory(rel_path("current/public"))
-
- expect(File).to be_symlink(rel_path("current"))
- expect(File.readlink(rel_path("current"))).to eq(rel_path("releases/#{latest_rev}"))
-
- # if callbacks ran, we know the app was deployed and not merely rolled
- # back to a (busted) prior deployment.
- expect(callback_order).to eq([:before_migrate,
- :before_symlink,
- :before_restart,
- :after_restart ])
- end
- end
-
- let!(:callback_order) { [] }
-
- let(:deploy_to_latest_with_callback_tracking) do
- resource = deploy_to_latest_rev.dup
- tracker = callback_order
- resource.before_migrate { tracker << :before_migrate }
- resource.before_symlink { tracker << :before_symlink }
- resource.before_restart { tracker << :before_restart }
- resource.after_restart { tracker << :after_restart }
- resource
- 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})
- deploy_to_latest_with_callback_tracking.run_action(:deploy)
- end
-
- let(:deploy_that_fails) do
- resource = deploy_to_latest_rev.dup
- 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'")
- resource
- end
-
- before do
- expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
- deploy_to_latest_with_callback_tracking.run_action(:deploy)
- end
-
- include_examples "a recovered deployment"
- end
-
- context "when cloning the app code" do
-
- class BadTimeScmProvider
- def initialize(new_resource, run_context)
- end
-
- def load_current_resource
- end
-
- def revision_slug
- "5"
- end
-
- def run_action(action)
- raise "network error"
- end
- end
-
- let(:deploy_that_fails) do
- resource = deploy_to_latest_rev.dup
- resource.scm_provider(BadTimeScmProvider)
- resource
- end
-
- before do
- expect { deploy_that_fails.run_action(:deploy) }.to raise_error(RuntimeError, /network error/)
- deploy_to_latest_with_callback_tracking.run_action(:deploy)
- end
-
- include_examples "a recovered deployment"
- 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
- end
-
- before do
- expect { deploy_that_fails.run_action(:deploy) }.to raise_error(Exception, %r{I am a failed deploy})
- deploy_to_latest_rev.run_action(:deploy)
- end
-
- 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/dnf_package_spec.rb b/spec/functional/resource/dnf_package_spec.rb
index 4c9ee6ca97..f05d297004 100644
--- a/spec/functional/resource/dnf_package_spec.rb
+++ b/spec/functional/resource/dnf_package_spec.rb
@@ -21,7 +21,7 @@ require "chef/mixin/shell_out"
# run this test only for following platforms.
exclude_test = !(%w{rhel fedora}.include?(ohai[:platform_family]) && File.exist?("/usr/bin/dnf"))
-describe Chef::Resource::RpmPackage, :requires_root, :external => exclude_test do
+describe Chef::Resource::RpmPackage, :requires_root, external: exclude_test do
include Chef::Mixin::ShellOut
def flush_cache
@@ -39,12 +39,12 @@ describe Chef::Resource::RpmPackage, :requires_root, :external => exclude_test d
before(:each) do
File.open("/etc/yum.repos.d/chef-dnf-localtesting.repo", "w+") do |f|
- f.write <<-EOF
-[chef-dnf-localtesting]
-name=Chef DNF spec testing repo
-baseurl=file://#{CHEF_SPEC_ASSETS}/yumrepo
-enable=1
-gpgcheck=0
+ f.write <<~EOF
+ [chef-dnf-localtesting]
+ name=Chef DNF spec testing repo
+ baseurl=file://#{CHEF_SPEC_ASSETS}/yumrepo
+ enable=1
+ gpgcheck=0
EOF
end
shell_out!("rpm -qa | grep chef_rpm | xargs -r rpm -e")
@@ -66,47 +66,47 @@ gpgcheck=0
flush_cache
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "does not install if the package is installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "does not install twice" do
flush_cache
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "does not install if the prior version package is installed" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "does not install if the i686 package is installed" do
skip "FIXME: do nothing, or install the x86_64 version?"
- preinstall("chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.i686.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.i686")
end
it "does not install if the prior version i686 package is installed" do
skip "FIXME: do nothing, or install the x86_64 version?"
- preinstall("chef_rpm-1.2-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.2-1.i686.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.i686")
end
end
@@ -116,7 +116,7 @@ gpgcheck=0
dnf_package.package_name("chef_rpm-1.10")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "works with an older version" do
@@ -124,15 +124,15 @@ gpgcheck=0
dnf_package.package_name("chef_rpm-1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "works with an evr" do
flush_cache
- dnf_package.package_name("chef_rpm-0:1.2-1.fc24")
+ dnf_package.package_name("chef_rpm-0:1.2-1")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "works with a version glob" do
@@ -140,7 +140,7 @@ gpgcheck=0
dnf_package.package_name("chef_rpm-1*")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "works with a name glob + version glob" do
@@ -148,7 +148,7 @@ gpgcheck=0
dnf_package.package_name("chef_rp*-1*")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
end
@@ -160,7 +160,7 @@ gpgcheck=0
dnf_package.version("1.10")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "matches with a glob" do
@@ -169,25 +169,25 @@ gpgcheck=0
dnf_package.version("1*")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "matches the vr" do
flush_cache
dnf_package.package_name("chef_rpm")
- dnf_package.version("1.10-1.fc24")
+ dnf_package.version("1.10-1")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "matches the evr" do
flush_cache
dnf_package.package_name("chef_rpm")
- dnf_package.version("0:1.10-1.fc24")
+ dnf_package.version("0:1.10-1")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "matches with a vr glob" do
@@ -197,7 +197,7 @@ gpgcheck=0
dnf_package.version("1.10-1*")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "matches with an evr glob" do
@@ -207,28 +207,28 @@ gpgcheck=0
dnf_package.version("0:1.10-1*")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
end
context "downgrades" do
it "just work with DNF" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.version("1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "throws a deprecation warning with allow_downgrade" do
Chef::Config[:treat_deprecation_warnings_as_errors] = false
expect(Chef).to receive(:deprecated).with(:dnf_package_allow_downgrade, /^the allow_downgrade property on the dnf_package provider is not used/)
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.version("1.2")
dnf_package.run_action(:install)
dnf_package.allow_downgrade true
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
@@ -238,7 +238,7 @@ gpgcheck=0
dnf_package.package_name("chef_rpm.x86_64")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "installs with 32-bit arch in the name" do
@@ -246,7 +246,7 @@ gpgcheck=0
dnf_package.package_name("chef_rpm.i686")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.i686")
end
it "installs with 64-bit arch in the property" do
@@ -255,7 +255,7 @@ gpgcheck=0
dnf_package.arch("x86_64")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "installs with 32-bit arch in the property" do
@@ -264,7 +264,7 @@ gpgcheck=0
dnf_package.arch("i686")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.i686")
end
end
@@ -274,23 +274,23 @@ gpgcheck=0
dnf_package.package_name("chef_rpm >= 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "when it is met, it does nothing" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.package_name("chef_rpm >= 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "when it is met, it does nothing" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name("chef_rpm >= 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "with nothing intalled, it installs the latest version" do
@@ -298,23 +298,23 @@ gpgcheck=0
dnf_package.package_name("chef_rpm > 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "when it is not met by an installed rpm, it upgrades" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.package_name("chef_rpm > 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "when it is met by an installed rpm, it does nothing" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name("chef_rpm > 1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "when there is no solution to the contraint" do
@@ -324,7 +324,7 @@ gpgcheck=0
end
it "when there is no solution to the contraint but an rpm is preinstalled" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name("chef_rpm > 2.0")
expect { dnf_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
end
@@ -349,61 +349,61 @@ gpgcheck=0
flush_cache
dnf_package.name "something"
dnf_package.package_name "somethingelse"
- dnf_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "installs the package when the name is a path to a file" do
flush_cache
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "does not downgrade the package with :install" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "does not upgrade the package with :install" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "is idempotent when the package is already installed" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
context "with no available version" do
it "works when a package is installed" do
FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "works with a local source" do
FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
flush_cache
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
@@ -413,12 +413,12 @@ gpgcheck=0
dnf_package.package_name([ "chef_rpm.x86_64", "chef_rpm.i686" ] )
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
it "does nothing if both are installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm", "chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm", "chef_rpm-1.10-1.i686.rpm")
flush_cache
dnf_package.package_name([ "chef_rpm.x86_64", "chef_rpm.i686" ] )
dnf_package.run_action(:install)
@@ -426,21 +426,21 @@ gpgcheck=0
end
it "installs the second rpm if the first is installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name([ "chef_rpm.x86_64", "chef_rpm.i686" ] )
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
it "installs the first rpm if the second is installed" do
- preinstall("chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.i686.rpm")
dnf_package.package_name([ "chef_rpm.x86_64", "chef_rpm.i686" ] )
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
# unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
@@ -450,35 +450,35 @@ gpgcheck=0
dnf_package.arch(%w{x86_64 i686})
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
# unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
it "installs the second rpm if the first is installed (muti-arch)" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name(%w{chef_rpm chef_rpm} )
dnf_package.arch(%w{x86_64 i686})
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
# unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
it "installs the first rpm if the second is installed (muti-arch)" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.package_name(%w{chef_rpm chef_rpm} )
dnf_package.arch(%w{x86_64 i686})
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.x86_64/)
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.fc24.i686/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.x86_64/)
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to match(/chef_rpm-1.10-1.i686/)
end
# unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
it "does nothing if both are installed (muti-arch)" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm", "chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm", "chef_rpm-1.10-1.i686.rpm")
dnf_package.package_name(%w{chef_rpm chef_rpm} )
dnf_package.arch(%w{x86_64 i686})
dnf_package.run_action(:install)
@@ -490,22 +490,22 @@ gpgcheck=0
describe ":upgrade" do
context "downgrades" do
it "just work with DNF" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.version("1.2")
dnf_package.run_action(:install)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "throws a deprecation warning with allow_downgrade" do
Chef::Config[:treat_deprecation_warnings_as_errors] = false
expect(Chef).to receive(:deprecated).with(:dnf_package_allow_downgrade, /^the allow_downgrade property on the dnf_package provider is not used/)
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.version("1.2")
dnf_package.run_action(:install)
dnf_package.allow_downgrade true
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
@@ -514,62 +514,62 @@ gpgcheck=0
flush_cache
dnf_package.name "something"
dnf_package.package_name "somethingelse"
- dnf_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "installs the package when the name is a path to a file" do
flush_cache
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "downgrades the package" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "upgrades the package" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
it "is idempotent when the package is already installed" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
context "with no available version" do
it "works when a package is installed" do
FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
it "works with a local source" do
FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
flush_cache
- dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.fc24.x86_64.rpm")
+ dnf_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:upgrade)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.x86_64")
end
end
end
@@ -585,14 +585,14 @@ gpgcheck=0
end
it "removes the package if the package is installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
end
it "does not remove the package twice" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
@@ -602,7 +602,7 @@ gpgcheck=0
end
it "removes the package if the prior version package is installed" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
@@ -610,7 +610,7 @@ gpgcheck=0
it "removes the package if the i686 package is installed" do
skip "FIXME: should this be fixed or is the current behavior correct?"
- preinstall("chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.i686.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
@@ -618,7 +618,7 @@ gpgcheck=0
it "removes the package if the prior version i686 package is installed" do
skip "FIXME: should this be fixed or is the current behavior correct?"
- preinstall("chef_rpm-1.2-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.2-1.i686.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
@@ -635,48 +635,48 @@ gpgcheck=0
end
it "removes the package if the package is installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
end
it "removes the package if the prior version package is installed" do
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
end
it "does nothing if the i686 package is installed" do
- preinstall("chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.i686.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.i686")
end
it "does nothing if the prior version i686 package is installed" do
- preinstall("chef_rpm-1.2-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.2-1.i686.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be false
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.fc24.i686")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.2-1.i686")
end
end
context "with 32-bit arch" do
let(:package_name) { "chef_rpm.i686" }
it "removes only the 32-bit arch if both are installed" do
- preinstall("chef_rpm-1.10-1.fc24.x86_64.rpm", "chef_rpm-1.10-1.fc24.i686.rpm")
+ preinstall("chef_rpm-1.10-1.x86_64.rpm", "chef_rpm-1.10-1.i686.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
- expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.fc24.x86_64")
+ expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("chef_rpm-1.10-1.x86_64")
end
end
context "with no available version" do
it "works when a package is installed" do
FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
- preinstall("chef_rpm-1.2-1.fc24.x86_64.rpm")
+ preinstall("chef_rpm-1.2-1.x86_64.rpm")
dnf_package.run_action(:remove)
expect(dnf_package.updated_by_last_action?).to be true
expect(shell_out("rpm -q chef_rpm").stdout.chomp).to eql("package chef_rpm is not installed")
diff --git a/spec/functional/resource/dsc_script_spec.rb b/spec/functional/resource/dsc_script_spec.rb
index ce92c468f0..1caa07d105 100644
--- a/spec/functional/resource/dsc_script_spec.rb
+++ b/spec/functional/resource/dsc_script_spec.rb
@@ -147,38 +147,38 @@ EOH
let(:dsc_user_suffix_code) { dsc_user_suffix }
let(:dsc_script_environment_attribute) { nil }
let(:dsc_user_resources_code) do
- <<-EOH
- #{config_param_section}
-node localhost
-{
-$testuser = #{dsc_user_code}
-$testpassword = ConvertTo-SecureString -String "jf9a8m49jrajf4#" -AsPlainText -Force
-$testcred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $testuser, $testpassword
-
-User dsctestusercreate
-{
- UserName = $testuser
- Password = $testcred
- Description = "DSC test user"
- Ensure = "Present"
- Disabled = $false
- PasswordNeverExpires = $true
- PasswordChangeRequired = $false
-}
-}
+ <<~EOH
+ #{config_param_section}
+ node localhost
+ {
+ $testuser = #{dsc_user_code}
+ $testpassword = ConvertTo-SecureString -String "jf9a8m49jrajf4#" -AsPlainText -Force
+ $testcred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $testuser, $testpassword
+
+ User dsctestusercreate
+ {
+ UserName = $testuser
+ Password = $testcred
+ Description = "DSC test user"
+ Ensure = "Present"
+ Disabled = $false
+ PasswordNeverExpires = $true
+ PasswordChangeRequired = $false
+ }
+ }
EOH
end
let(:dsc_user_config_data) do
- <<-EOH
-@{
- AllNodes = @(
- @{
- NodeName = "localhost";
- PSDscAllowPlainTextPassword = $true
- }
- )
-}
+ <<~EOH
+ @{
+ AllNodes = @(
+ @{
+ NodeName = "localhost";
+ PSDscAllowPlainTextPassword = $true
+ }
+ )
+ }
EOH
end
@@ -188,17 +188,17 @@ EOH
let(:dsc_environment_fail_etc_directory) { "#{ENV['systemroot']}\\system32\\drivers\\etc" }
let(:exception_message_signature) { "LL927-LL928" }
let(:dsc_environment_config) do
- <<-EOH
-if (($pwd.path -eq '#{dsc_environment_fail_etc_directory}') -and (test-path('#{dsc_environment_fail_etc_directory}')))
-{
- throw 'Signature #{exception_message_signature}: Purposefully failing because cwd == #{dsc_environment_fail_etc_directory}'
-}
-environment "whatsmydir"
-{
- Name = '#{dsc_environment_env_var_name}'
- Value = $pwd.path
- Ensure = 'Present'
-}
+ <<~EOH
+ if (($pwd.path -eq '#{dsc_environment_fail_etc_directory}') -and (test-path('#{dsc_environment_fail_etc_directory}')))
+ {
+ throw 'Signature #{exception_message_signature}: Purposefully failing because cwd == #{dsc_environment_fail_etc_directory}'
+ }
+ environment "whatsmydir"
+ {
+ Name = '#{dsc_environment_env_var_name}'
+ Value = $pwd.path
+ Ensure = 'Present'
+ }
EOH
end
@@ -234,7 +234,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 +243,12 @@ EOH
shared_examples_for "a dsc_script resource with configuration affected by cwd" do
after(:each) do
removal_resource = Chef::Resource::DscScript.new(dsc_test_resource_name, dsc_test_run_context)
- removal_resource.code <<-EOH
-environment 'removethis'
-{
- Name = '#{dsc_environment_env_var_name}'
- Ensure = 'Absent'
-}
+ removal_resource.code <<~EOH
+ environment 'removethis'
+ {
+ Name = '#{dsc_environment_env_var_name}'
+ Ensure = 'Absent'
+ }
EOH
removal_resource.run_action(:run)
end
@@ -314,7 +314,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
end
end
@@ -347,7 +347,7 @@ 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).to_s, :"#{dsc_user_suffix_param_name}" => (dsc_user_suffix).to_s } }
it "does not directly contain the user name" do
configuration_script_content = ::File.open(dsc_test_resource.command) do |file|
file.read
@@ -409,45 +409,45 @@ EOH
end
let(:dsc_configuration_script) do
- <<-MYCODE
-cd c:\\
-configuration LCM
-{
- param ($thumbprint)
- localconfigurationmanager
- {
- RebootNodeIfNeeded = $false
- ConfigurationMode = 'ApplyOnly'
- CertificateID = $thumbprint
- }
-}
-$cert = ls Cert:\\LocalMachine\\My\\ |
- Where-Object {$_.Subject -match "ChefTest"} |
- Select -first 1
-
-if($cert -eq $null) {
- $pfxpath = '#{self_signed_cert_path}'
- $password = ''
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($pfxpath, $password, ([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeyset))
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store "My", ([System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
- $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
- $store.Add($cert)
- $store.Close()
-}
-
-lcm -thumbprint $cert.thumbprint
-set-dsclocalconfigurationmanager -path ./LCM
-$ConfigurationData = @"
-@{
-AllNodes = @(
- @{
- NodeName = "localhost";
- CertificateID = '$($cert.thumbprint)';
- };
-);
-}
-"@
-$ConfigurationData | out-file '#{configuration_data_path}' -force
+ <<~MYCODE
+ cd c:\\
+ configuration LCM
+ {
+ param ($thumbprint)
+ localconfigurationmanager
+ {
+ RebootNodeIfNeeded = $false
+ ConfigurationMode = 'ApplyOnly'
+ CertificateID = $thumbprint
+ }
+ }
+ $cert = ls Cert:\\LocalMachine\\My\\ |
+ Where-Object {$_.Subject -match "ChefTest"} |
+ Select -first 1
+
+ if($cert -eq $null) {
+ $pfxpath = '#{self_signed_cert_path}'
+ $password = ''
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($pfxpath, $password, ([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeyset))
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store "My", ([System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine)
+ $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
+ $store.Add($cert)
+ $store.Close()
+ }
+
+ lcm -thumbprint $cert.thumbprint
+ set-dsclocalconfigurationmanager -path ./LCM
+ $ConfigurationData = @"
+ @{
+ AllNodes = @(
+ @{
+ NodeName = "localhost";
+ CertificateID = '$($cert.thumbprint)';
+ };
+ );
+ }
+ "@
+ $ConfigurationData | out-file '#{configuration_data_path}' -force
MYCODE
end
@@ -460,13 +460,13 @@ $ConfigurationData | out-file '#{configuration_data_path}' -force
let(:dsc_script_resource) do
dsc_test_resource_base.tap do |r|
- r.code <<-EOF
-User dsctestusercreate
-{
- UserName = '#{dsc_user}'
- Password = #{r.ps_credential('jf9a8m49jrajf4#')}
- Ensure = "Present"
-}
+ r.code <<~EOF
+ User dsctestusercreate
+ {
+ UserName = '#{dsc_user}'
+ Password = #{r.ps_credential('jf9a8m49jrajf4#')}
+ Ensure = "Present"
+ }
EOF
r.configuration_data_script(configuration_data_path)
end
diff --git a/spec/functional/resource/env_spec.rb b/spec/functional/resource/env_spec.rb
deleted file mode 100755
index 4b0ff70c0b..0000000000
--- a/spec/functional/resource/env_spec.rb
+++ /dev/null
@@ -1,192 +0,0 @@
-#
-# Author:: Adam Edwards (<adamed@chef.io>)
-# Copyright:: Copyright 2014-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Resource::Env, :windows_only do
- context "when running on Windows" do
- let(:chef_env_test_lower_case) { "chefenvtest" }
- let(:chef_env_test_mixed_case) { "chefENVtest" }
- let(:env_dne_key) { "env_dne_key" }
- let(:env_value1) { "value1" }
- let(:env_value2) { "value2" }
-
- let(:env_value_expandable) { "%SystemRoot%" }
- let(:test_run_context) do
- node = Chef::Node.new
- node.default["os"] = "windows"
- node.default["platform"] = "windows"
- node.default["platform_version"] = "6.1"
- empty_events = Chef::EventDispatch::Dispatcher.new
- Chef::RunContext.new(node, {}, empty_events)
- end
- let(:test_resource) do
- Chef::Resource::Env.new("unknown", test_run_context)
- end
-
- before(:each) do
- resource_lower = Chef::Resource::Env.new(chef_env_test_lower_case, test_run_context)
- resource_lower.run_action(:delete)
- resource_mixed = Chef::Resource::Env.new(chef_env_test_mixed_case, test_run_context)
- resource_mixed.run_action(:delete)
- end
-
- context "when the create action is invoked" do
- it "should create an environment variable for action create" 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)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- end
-
- it "should modify an existing variable's value to a new value" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.value(env_value2)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
- end
-
- it "should modify an existing variable's value to a new value if the variable name case differs from the existing variable" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.key_name(chef_env_test_mixed_case)
- test_resource.value(env_value2)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
- end
-
- it "should not expand environment variables if the variable is not PATH" do
- expect(ENV[chef_env_test_lower_case]).to eq(nil)
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value_expandable)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value_expandable)
- end
- end
-
- context "when the modify action is invoked" do
- it "should raise an exception for modify if the variable doesn't exist" 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)
- end
-
- it "should modify an existing variable's value to a new value" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.value(env_value2)
- test_resource.run_action(:modify)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
- end
-
- # This examlpe covers Chef Issue #1754
- it "should modify an existing variable's value to a new value if the variable name case differs from the existing variable" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.key_name(chef_env_test_mixed_case)
- test_resource.value(env_value2)
- test_resource.run_action(:modify)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
- end
-
- it "should not expand environment variables if the variable is not PATH" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.value(env_value_expandable)
- test_resource.run_action(:modify)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value_expandable)
- end
-
- context "when using PATH" do
- let(:random_name) { Time.now.to_i }
- 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"] }
-
- it "should expand PATH" do
- expect(path_before).not_to include(env_val)
- test_resource.key_name("PATH")
- test_resource.value("#{path_before};#{env_val}")
- test_resource.run_action(:create)
- expect(ENV["PATH"]).not_to include(env_val)
- expect(ENV["PATH"]).to include("#{random_name}")
- end
-
- after(:each) do
- # cleanup so we don't flood the path
- test_resource.key_name("PATH")
- test_resource.value(path_before)
- test_resource.run_action(:create)
- ENV["PATH"] = env_path_before
- end
- end
-
- end
-
- context "when the delete action is invoked" do
- it "should delete an environment variable" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.run_action(:delete)
- expect(ENV[chef_env_test_lower_case]).to eq(nil)
- end
-
- it "should not raise an exception when a non-existent environment variable is deleted" 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(ENV[chef_env_test_lower_case]).to eq(nil)
- end
-
- it "should delete an existing variable's value to a new value if the specified variable name case differs from the existing variable" do
- test_resource.key_name(chef_env_test_lower_case)
- test_resource.value(env_value1)
- test_resource.run_action(:create)
- expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
- test_resource.key_name(chef_env_test_mixed_case)
- test_resource.run_action(:delete)
- expect(ENV[chef_env_test_lower_case]).to eq(nil)
- expect(ENV[chef_env_test_mixed_case]).to eq(nil)
- end
-
- it "should delete a value from the current process even if it is not in the registry" do
- expect(ENV[env_dne_key]).to eq(nil)
- ENV[env_dne_key] = env_value1
- test_resource.key_name(env_dne_key)
- test_resource.run_action(:delete)
- expect(ENV[env_dne_key]).to eq(nil)
- end
- end
- end
-end
diff --git a/spec/functional/resource/execute_spec.rb b/spec/functional/resource/execute_spec.rb
index c0956c5594..3ad8762169 100644
--- a/spec/functional/resource/execute_spec.rb
+++ b/spec/functional/resource/execute_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Serdar Sutay (<serdar@chef.io>)
-# Copyright:: Copyright 2014-2017, Chef Software Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -51,7 +51,7 @@ describe Chef::Resource::Execute do
# why_run mode doesn't disable the updated_by_last_action logic, so we really have to look at the provider action
# to see if why_run correctly disabled the resource. It should shell_out! for the guard but not the resource.
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_with_systems_locale!).once
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out!).once
resource.only_if guard
resource.run_action(:run)
@@ -106,7 +106,7 @@ describe Chef::Resource::Execute do
it "guard adds additional values in its :environment and runs" do
resource.only_if %{ruby -e 'exit 1 if ENV["SGCE_SECRET"] != "regularsecret"'}, {
- :environment => { "SGCE_SECRET" => "regularsecret" },
+ environment: { "SGCE_SECRET" => "regularsecret" },
}
resource.run_action(:run)
expect(resource).to be_updated_by_last_action
@@ -114,7 +114,7 @@ describe Chef::Resource::Execute do
it "guard adds additional values in its :environment and does not run" do
resource.only_if %{ruby -e 'exit 1 if ENV["SGCE_SECRET"] == "regularsecret"'}, {
- :environment => { "SGCE_SECRET" => "regularsecret" },
+ environment: { "SGCE_SECRET" => "regularsecret" },
}
resource.run_action(:run)
expect(resource).not_to be_updated_by_last_action
@@ -122,7 +122,7 @@ describe Chef::Resource::Execute do
it "guard overwrites value with its :environment and runs" do
resource.only_if %{ruby -e 'exit 1 if ENV["SAWS_SECRET"] != "regularsecret"'}, {
- :environment => { "SAWS_SECRET" => "regularsecret" },
+ environment: { "SAWS_SECRET" => "regularsecret" },
}
resource.run_action(:run)
expect(resource).to be_updated_by_last_action
@@ -130,7 +130,7 @@ describe Chef::Resource::Execute do
it "guard overwrites value with its :environment and does not runs" do
resource.only_if %{ruby -e 'exit 1 if ENV["SAWS_SECRET"] == "regularsecret"'}, {
- :environment => { "SAWS_SECRET" => "regularsecret" },
+ environment: { "SAWS_SECRET" => "regularsecret" },
}
resource.run_action(:run)
expect(resource).not_to be_updated_by_last_action
diff --git a/spec/functional/resource/file_spec.rb b/spec/functional/resource/file_spec.rb
index 0fa1317032..291311f3e2 100644
--- a/spec/functional/resource/file_spec.rb
+++ b/spec/functional/resource/file_spec.rb
@@ -51,7 +51,7 @@ describe Chef::Resource::File do
end
let(:resource_with_relative_path) do
- create_resource(:use_relative_path => true)
+ create_resource(use_relative_path: true)
end
let(:unmanaged_content) do
diff --git a/spec/functional/resource/git_spec.rb b/spec/functional/resource/git_spec.rb
index 6808898c29..16cde6351a 100644
--- a/spec/functional/resource/git_spec.rb
+++ b/spec/functional/resource/git_spec.rb
@@ -22,7 +22,7 @@ require "tmpdir"
require "shellwords"
# Deploy relies heavily on symlinks, so it doesn't work on windows.
-describe Chef::Resource::Git, :requires_git => true do
+describe Chef::Resource::Git, requires_git: true do
include Chef::Mixin::ShellOut
let(:file_cache_path) { Dir.mktmpdir }
# Some versions of git complains when the deploy directory is
@@ -65,17 +65,17 @@ describe Chef::Resource::Git, :requires_git => true do
let(:rev_head) { "d294fbfd05aa7709ad9a9b8ef6343b17d355bf5f" }
let(:git_user_config) do
- <<-E
-[user]
- name = frodoTbaggins
- email = frodo@shire.org
+ <<~E
+ [user]
+ name = frodoTbaggins
+ email = frodo@shire.org
E
end
before(:each) do
Chef::Log.level = :warn # silence git command live streams
@old_file_cache_path = Chef::Config[:file_cache_path]
- shell_out!("git clone \"#{git_bundle_repo}\" example", :cwd => origin_repo_dir)
+ 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) }
Chef::Config[:file_cache_path] = file_cache_path
end
@@ -127,10 +127,10 @@ E
it "checks out the revision pointed to by the tag commit, not the tag commit itself" do
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(v1_commit)
# also verify the tag commit itself is what we expect as an extra sanity check
- rev = shell_out!("git rev-parse v1.0.0", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ rev = shell_out!("git rev-parse v1.0.0", cwd: deploy_directory, returns: [0]).stdout.strip
expect(rev).to eq(v1_tag)
end
@@ -138,7 +138,7 @@ E
# this used to fail because we didn't resolve the annotated tag
# properly to the pointed to commit.
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(v1_commit)
copy_git_resource.run_action(:sync)
@@ -164,14 +164,14 @@ E
it "checks out the expected revision ed18" do
basic_git_resource.revision rev_foo
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(rev_foo)
end
it "doesn't update if up-to-date" do
basic_git_resource.revision rev_foo
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(rev_foo)
copy_git_resource.revision rev_foo
@@ -182,7 +182,7 @@ E
it "checks out the expected revision 972d" do
basic_git_resource.revision rev_testing
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(rev_testing)
end
end
@@ -197,7 +197,7 @@ E
it "checks out the expected revision" do
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(rev_head)
end
end
@@ -212,7 +212,7 @@ E
it "checks out HEAD as the default revision" do
basic_git_resource.run_action(:sync)
- head_rev = shell_out!("git rev-parse HEAD", :cwd => deploy_directory, :returns => [0]).stdout.strip
+ head_rev = shell_out!("git rev-parse HEAD", cwd: deploy_directory, returns: [0]).stdout.strip
expect(head_rev).to eq(rev_head)
end
end
@@ -220,7 +220,7 @@ E
context "when dealing with a repo with a degenerate tag named 'HEAD'" do
before do
shell_out!("git tag -m\"degenerate tag\" HEAD ed181b3419b6f489bedab282348162a110d6d3a1",
- :cwd => origin_repo)
+ cwd: origin_repo)
end
let(:basic_git_resource) do
@@ -240,16 +240,16 @@ E
it "checks out the (master) HEAD revision and ignores the tag" do
basic_git_resource.run_action(:sync)
head_rev = shell_out!("git rev-parse HEAD",
- :cwd => deploy_directory,
- :returns => [0]).stdout.strip
+ cwd: deploy_directory,
+ returns: [0]).stdout.strip
expect(head_rev).to eq(rev_head)
end
it "checks out the (master) HEAD revision when no revision is specified (ignores tag)" do
git_resource_default_rev.run_action(:sync)
head_rev = shell_out!("git rev-parse HEAD",
- :cwd => deploy_directory,
- :returns => [0]).stdout.strip
+ cwd: deploy_directory,
+ returns: [0]).stdout.strip
expect(head_rev).to eq(rev_head)
end
diff --git a/spec/functional/resource/group_spec.rb b/spec/functional/resource/group_spec.rb
index 03c14382e9..ea9aa5c2b7 100644
--- a/spec/functional/resource/group_spec.rb
+++ b/spec/functional/resource/group_spec.rb
@@ -81,7 +81,7 @@ describe Chef::Resource::Group, :requires_root_or_running_windows, :not_supporte
if user && domain != "."
computer_name = ENV["computername"]
- !domain.casecmp(computer_name.downcase).zero?
+ !domain.casecmp(computer_name.downcase) == 0
end
end
diff --git a/spec/functional/resource/ifconfig_spec.rb b/spec/functional/resource/ifconfig_spec.rb
index 0298dbcf45..c52a4c0694 100644
--- a/spec/functional/resource/ifconfig_spec.rb
+++ b/spec/functional/resource/ifconfig_spec.rb
@@ -16,13 +16,14 @@
# limitations under the License.
#
+require "spec_helper"
require "functional/resource/base"
require "chef/mixin/shell_out"
# run this test only for following platforms.
-include_flag = !(%w{ubuntu centos aix}.include?(ohai[:platform]))
+include_flag = !(%w{amazon debian aix}.include?(ohai[:platform_family]) || (ohai[:platform_family] == "rhel" && ohai[:platform_version].to_i < 7))
-describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => include_flag do
+describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, external: include_flag do
# This test does not work in travis because there is no eth0
include Chef::Mixin::ShellOut
@@ -52,7 +53,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => in
end
def fetch_first_interface_name
- shell_out("ifconfig | grep Ethernet | head -1 | cut -d' ' -f1").stdout.strip
+ shell_out("ip link list |grep UP|grep -vi loop|head -1|cut -d':' -f 2").stdout.strip
end
# **Caution: any updates to core interfaces can be risky.
@@ -121,7 +122,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => in
end
exclude_test = ohai[:platform] != "ubuntu"
- describe "#action_add", :external => exclude_test do
+ describe "#action_add", external: exclude_test do
after do
new_resource.run_action(:delete)
end
@@ -133,7 +134,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => in
end
end
- describe "#action_enable", :external => exclude_test do
+ describe "#action_enable", external: exclude_test do
after do
new_resource.run_action(:disable)
end
@@ -144,7 +145,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => in
end
end
- describe "#action_disable", :external => exclude_test do
+ describe "#action_disable", external: exclude_test do
before do
setup_enable_interface(new_resource)
new_resource.run_action(:enable)
@@ -156,7 +157,7 @@ describe Chef::Resource::Ifconfig, :requires_root, :skip_travis, :external => in
end
end
- describe "#action_delete", :external => exclude_test do
+ describe "#action_delete", external: exclude_test do
before do
setup_add_interface(new_resource)
new_resource.run_action(:add)
diff --git a/spec/functional/resource/link_spec.rb b/spec/functional/resource/link_spec.rb
index e8a95436f7..4464b6ed69 100644
--- a/spec/functional/resource/link_spec.rb
+++ b/spec/functional/resource/link_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
if windows?
- require "chef/win32/file" #probably need this in spec_helper
+ require "chef/win32/file" # probably need this in spec_helper
require "chef/win32/security"
end
@@ -27,6 +27,7 @@ describe Chef::Resource::Link do
let(:file_base) { "file_spec" }
let(:expect_updated?) { true }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
# We create the files in a different directory than tmp to exercise
# different file deployment strategies more completely.
@@ -163,6 +164,7 @@ describe Chef::Resource::Link do
cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks"))
cookbook_collection = Chef::CookbookCollection.new(Chef::CookbookLoader.new(cookbook_repo))
run_context = Chef::RunContext.new(node, cookbook_collection, events)
+ allow(run_context).to receive(:logger).and_return(logger)
resource = Chef::Resource::Link.new(target_file, run_context)
resource.to(to)
resource
@@ -172,7 +174,7 @@ describe Chef::Resource::Link do
create_resource
end
- describe "when supported on platform", :not_supported_on_win2k3 do
+ describe "when supported on platform" do
shared_examples_for "delete errors out" do
it "delete errors out" do
expect { resource.run_action(:delete) }.to raise_error(Chef::Exceptions::Link)
@@ -184,7 +186,7 @@ describe Chef::Resource::Link do
describe "the :delete action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:delete)
end
@@ -205,7 +207,7 @@ describe Chef::Resource::Link do
describe "the :delete action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:delete)
end
@@ -226,7 +228,7 @@ describe Chef::Resource::Link do
describe "the :create action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:create)
end
@@ -248,7 +250,7 @@ describe Chef::Resource::Link do
describe "the :create action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:create)
end
@@ -270,7 +272,7 @@ describe Chef::Resource::Link do
describe "the :create action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:create)
end
it "preserves the hard link" do
@@ -295,7 +297,7 @@ describe Chef::Resource::Link do
describe "the :create action" do
before(:each) do
@info = []
- allow(Chef::Log).to receive(:info) { |msg| @info << msg }
+ allow(logger).to receive(:info) { |msg| @info << msg }
resource.run_action(:create)
end
it "links to the target file" do
@@ -694,10 +696,4 @@ describe Chef::Resource::Link do
end
end
end
-
- describe "when not supported on platform", :win2k3_only do
- it "raises error" do
- expect { resource }.to raise_error(Chef::Exceptions::Win32APIFunctionNotImplemented)
- end
- end
end
diff --git a/spec/functional/resource/mount_spec.rb b/spec/functional/resource/mount_spec.rb
index c756b0d3d4..f4e528c755 100644
--- a/spec/functional/resource/mount_spec.rb
+++ b/spec/functional/resource/mount_spec.rb
@@ -22,9 +22,9 @@ require "chef/mixin/shell_out"
require "tmpdir"
# run this test only for following platforms.
-include_flag = !(%w{ubuntu centos aix solaris2}.include?(ohai[:platform]))
+include_flag = !(%w{debian rhel amazon aix solaris2}.include?(ohai[:platform_family]))
-describe Chef::Resource::Mount, :requires_root, :skip_travis, :external => include_flag do
+describe Chef::Resource::Mount, :requires_root, :skip_travis, external: include_flag do
# Disabled in travis because it refuses to let us mount a ramdisk. /dev/ramX does not
# exist even after loading the kernel module
@@ -35,15 +35,19 @@ describe Chef::Resource::Mount, :requires_root, :skip_travis, :external => inclu
def setup_device_for_mount
# use ramdisk for creating a test device for mount.
# This can cleaner if we have chef resource/provider for ramdisk.
- case ohai[:platform]
+ case ohai[:platform_family]
when "aix"
# On AIX, we can't create a ramdisk inside a WPAR, so we use
# a "namefs" mount against / to test
# https://www-304.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.performance/namefs_file_sys.htm
device = "/"
fstype = "namefs"
- when "ubuntu", "centos"
+ when "debian", "rhel", "amazon"
device = "/dev/ram1"
+ unless File.exist?(device)
+ shell_out("mknod -m 660 #{device} b 1 0")
+ shell_out("chown root:disk #{device}")
+ end
shell_out("ls -1 /dev/ram*").stdout.each_line do |d|
if shell_out("mount | grep #{d}").exitstatus == "1"
# this device is not mounted, so use it.
@@ -157,7 +161,7 @@ describe Chef::Resource::Mount, :requires_root, :skip_travis, :external => inclu
# don't run the remount tests on solaris2 (tmpfs does not support remount)
# Need to make sure the platforms we've already excluded are considered:
skip_remount = include_flag || (ohai[:platform] == "solaris2")
- describe "when the filesystem should be remounted and the resource supports remounting", :external => skip_remount do
+ describe "when the filesystem should be remounted and the resource supports remounting", external: skip_remount do
it "should remount the filesystem if it is mounted" do
new_resource.run_action(:mount)
mount_should_exist(new_resource.mount_point, new_resource.device)
diff --git a/spec/functional/resource/powershell_script_spec.rb b/spec/functional/resource/powershell_script_spec.rb
index af345b0ea4..cc1bd8fd1c 100644
--- a/spec/functional/resource/powershell_script_spec.rb
+++ b/spec/functional/resource/powershell_script_spec.rb
@@ -36,8 +36,6 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do
let(:cmdlet_exit_code_success_content) { "get-item ." }
let(:windows_process_exit_code_success_content) { "#{ENV['SystemRoot']}\\system32\\attrib.exe $env:systemroot" }
let(:windows_process_exit_code_not_found_content) { "findstr /notavalidswitch" }
- # Note that process exit codes on 32-bit Win2k3 cannot
- # exceed maximum value of signed integer
let(:arbitrary_nonzero_process_exit_code) { 4193 }
let(:arbitrary_nonzero_process_exit_code_content) { "exit #{arbitrary_nonzero_process_exit_code}" }
let(:invalid_powershell_interpreter_flag) { "/thisflagisinvalid" }
@@ -257,16 +255,16 @@ describe Chef::Resource::WindowsScript::PowershellScript, :windows_only do
context "when dsc is supported", :windows_powershell_dsc_only do
it "can execute LCM configuration code" do
- resource.code <<-EOF
-configuration LCM
-{
- param ($thumbprint)
- localconfigurationmanager
- {
- RebootNodeIfNeeded = $false
- ConfigurationMode = 'ApplyOnly'
- }
-}
+ resource.code <<~EOF
+ configuration LCM
+ {
+ param ($thumbprint)
+ localconfigurationmanager
+ {
+ RebootNodeIfNeeded = $false
+ ConfigurationMode = 'ApplyOnly'
+ }
+ }
EOF
expect { resource.run_action(:run) }.not_to raise_error
end
@@ -476,13 +474,13 @@ configuration LCM
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
@@ -583,7 +581,7 @@ configuration LCM
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
+ resource.only_if "$true", architecture: :i386
expect { resource.run_action(:run) }.to raise_error(
Chef::Exceptions::Win32ArchitectureIncorrect,
/cannot execute script with requested architecture 'i386' on Windows Nano Server/)
diff --git a/spec/functional/resource/reboot_spec.rb b/spec/functional/resource/reboot_spec.rb
index c264b122a7..3b8e3efe8a 100644
--- a/spec/functional/resource/reboot_spec.rb
+++ b/spec/functional/resource/reboot_spec.rb
@@ -22,9 +22,9 @@ describe Chef::Resource::Reboot do
let(:expected) do
{
- :delay_mins => 5,
- :requested_by => "reboot resource functional test",
- :reason => "reboot resource spec test",
+ delay_mins: 5,
+ requested_by: "reboot resource functional test",
+ reason: "reboot resource spec test",
}
end
diff --git a/spec/functional/resource/registry_spec.rb b/spec/functional/resource/registry_spec.rb
index b6767d47a3..8de6577759 100644
--- a/spec/functional/resource/registry_spec.rb
+++ b/spec/functional/resource/registry_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Prajakta Purohit (<prajakta@chef.io>)
# Author:: Lamont Granquist (<lamont@chef.io>)
-# Copyright:: Copyright 2011-2016, Chef Software Inc.
+# Copyright:: Copyright 2011-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -34,13 +34,13 @@ describe Chef::Resource::RegistryKey, :unix_only do
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" }])
+ @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
+describe Chef::Resource::RegistryKey, :windows_only, broken: true do
# parent and key must be single keys, not paths
let(:parent) { "Opscode" }
@@ -107,7 +107,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
reset_registry
end
- #Reporting setup
+ # Reporting setup
before do
@node.name("windowsbox")
@@ -123,7 +123,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
@run_id = @resource_reporter.run_id
@new_resource.cookbook_name = "monkey"
- @cookbook_version = double("Cookbook::Version", :version => "1.2.3")
+ @cookbook_version = double("Cookbook::Version", version: "1.2.3")
@new_resource.cookbook_version(@cookbook_version)
end
@@ -137,114 +137,114 @@ 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 "does not create the key if it already exists with same value and type but datatype of data differs" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "number", :type => :dword, :data => "12345" }])
+ @new_resource.values([{ name: "number", type: :dword, data: "12345" }])
@new_resource.run_action(:create)
expect(@new_resource).not_to be_updated_by_last_action
expect(@registry.key_exists?(reg_child)).to eq(true)
- expect(@registry.data_exists?(reg_child, { :name => "number", :type => :dword, :data => 12344 })).to eq(true)
+ expect(@registry.data_exists?(reg_child, { name: "number", type: :dword, data: 12344 })).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 => %w{OpscodeOrange Rules} }])
+ @new_resource.values([{ name: "Chef", type: :multi_string, data: %w{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 => %w{OpscodeOrange Rules} })).to eq(true)
+ expect(@registry.value_exists?(reg_child + '\OpscodeTest', { name: "Chef", type: :multi_string, data: %w{OpscodeOrange Rules} })).to eq(true)
end
it "raises an 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)
end
it "raises an error if action create and type key missing in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :data => "my_data" }])
+ @new_resource.values([{ name: "OC", data: "my_data" }])
expect { @new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::RegKeyValuesTypeMissing)
end
it "raises an error if action create and data key missing in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :type => :string }])
+ @new_resource.values([{ name: "OC", type: :string }])
expect { @new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::RegKeyValuesDataMissing)
end
it "raises an error if action create and only name key present in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC" }])
+ @new_resource.values([{ name: "OC" }])
expect { @new_resource.run_action(:create) }.to raise_error(Chef::Exceptions::RegKeyValuesTypeMissing)
end
it "does not raise an error if action create and all keys are present in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :type => :string, :data => "my_data" }])
+ @new_resource.values([{ name: "OC", type: :string, data: "my_data" }])
expect { @new_resource.run_action(:create) }.to_not raise_error
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)
- @new_resource.values.each do |value|
+ @new_resource.each_value do |value|
expect(@registry.value_exists?(reg_child, value)).to eq(true)
end
end
@@ -259,12 +259,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
@@ -272,7 +272,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
@@ -281,8 +281,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")
@@ -296,7 +296,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
it "does not raise 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)
@@ -305,7 +305,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
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)
@@ -313,28 +313,28 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
it "does not raise an exception if the action create and type key missing in values hash" do
@new_resource.key(reg_child + '\Slitheen')
- @new_resource.values([{ :name => "BriskWalk", :data => "my_data" }])
+ @new_resource.values([{ name: "BriskWalk", data: "my_data" }])
@new_resource.run_action(:create) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false)
end
it "does not raise an exception if the action create and data key missing in values hash" do
@new_resource.key(reg_child + '\Slitheen')
- @new_resource.values([{ :name => "BriskWalk", :type => :string }])
+ @new_resource.values([{ name: "BriskWalk", type: :string }])
@new_resource.run_action(:create) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false)
end
it "does not raise an exception if the action create and only name key present in values hash" do
@new_resource.key(reg_child + '\Slitheen')
- @new_resource.values([{ :name => "BriskWalk" }])
+ @new_resource.values([{ name: "BriskWalk" }])
@new_resource.run_action(:create) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false)
end
it "does not raise an exception if the action create and all keys are present in values hash" do
@new_resource.key(reg_child + '\Slitheen')
- @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "my_data" }])
+ @new_resource.values([{ name: "BriskWalk", type: :string, data: "my_data" }])
@new_resource.run_action(:create) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Slitheen')).to eq(false)
end
@@ -348,96 +348,96 @@ 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 => %w{OpscodeOrange Rules} }])
+ @new_resource.values([{ name: "Chef", type: :multi_string, data: %w{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 => %w{OpscodeOrange Rules} })).to eq(true)
+ expect(@registry.value_exists?(reg_child + '\Pyrovile', { name: "Chef", type: :multi_string, data: %w{OpscodeOrange Rules} })).to eq(true)
end
it "raises an 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)
end
it "raises an error if action create_if_missing and type key missing in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :data => "my_data" }])
+ @new_resource.values([{ name: "OC", data: "my_data" }])
expect { @new_resource.run_action(:create_if_missing) }.to raise_error(Chef::Exceptions::RegKeyValuesTypeMissing)
end
it "raises an error if action create_if_missing and data key missing in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :type => :string }])
+ @new_resource.values([{ name: "OC", type: :string }])
expect { @new_resource.run_action(:create_if_missing) }.to raise_error(Chef::Exceptions::RegKeyValuesDataMissing)
end
it "raises an error if action create_if_missing and only name key present in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC" }])
+ @new_resource.values([{ name: "OC" }])
expect { @new_resource.run_action(:create_if_missing) }.to raise_error(Chef::Exceptions::RegKeyValuesTypeMissing)
end
it "does not raise an error if action create_if_missing and all keys are present in values hash" do
@new_resource.key(reg_child)
- @new_resource.values([{ :name => "OC", :type => :string, :data => "my_data" }])
+ @new_resource.values([{ name: "OC", type: :string, data: "my_data" }])
expect { @new_resource.run_action(:create_if_missing) }.to_not raise_error
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)
- @new_resource.values.each do |value|
+ @new_resource.each_value do |value|
expect(@registry.value_exists?(reg_child + '\Adipose', value)).to eq(true)
end
end
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
@@ -446,7 +446,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")
@@ -460,7 +460,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
it "does not raise 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)
@@ -469,7 +469,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
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)
@@ -477,28 +477,28 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
it "does not raise an exception if the action create_if_missing and type key missing in values hash" do
@new_resource.key(reg_child + '\Zygons')
- @new_resource.values([{ :name => "BriskWalk", :data => "my_data" }])
+ @new_resource.values([{ name: "BriskWalk", data: "my_data" }])
@new_resource.run_action(:create_if_missing) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false)
end
it "does not raise an exception if the action create_if_missing and data key missing in values hash" do
@new_resource.key(reg_child + '\Zygons')
- @new_resource.values([{ :name => "BriskWalk", :type => :string }])
+ @new_resource.values([{ name: "BriskWalk", type: :string }])
@new_resource.run_action(:create_if_missing) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false)
end
it "does not raise an exception if the action create_if_missing and only name key present in values hash" do
@new_resource.key(reg_child + '\Zygons')
- @new_resource.values([{ :name => "BriskWalk" }])
+ @new_resource.values([{ name: "BriskWalk" }])
@new_resource.run_action(:create_if_missing) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false)
end
it "does not raise an exception if the action create_if_missing and all keys are present in values hash" do
@new_resource.key(reg_child + '\Zygons')
- @new_resource.values([{ :name => "BriskWalk", :type => :string, :data => "my_data" }])
+ @new_resource.values([{ name: "BriskWalk", type: :string, data: "my_data" }])
@new_resource.run_action(:create_if_missing) # should not raise_error
expect(@registry.key_exists?(reg_child + '\Zygons')).to eq(false)
end
@@ -522,54 +522,54 @@ 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 => %w{SeattleGrey OCOrange} }])
+ @new_resource.values([{ name: "LooksLike", type: :multi_string, data: %w{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 => %w{Seattle Washington} }, { :name => "AKA", :type => :string, :data => "OC" }])
+ @new_resource.values([{ name: "Opscode", type: :multi_string, data: %w{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 => %w{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: %w{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 => %w{Black Orange} }])
+ @new_resource.values([{ name: "Color", type: :multi_string, data: %w{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" }])
- #Not testing for after values to match since after -> new_resource values.
+ 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")
expect(@report["total_res_count"]).to eq("1")
@@ -581,7 +581,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)
@@ -622,7 +622,7 @@ describe Chef::Resource::RegistryKey, :windows_only, :broken => true do
it "ignores the values under a key" do
@new_resource.key(reg_parent + '\OpscodeIgnoredValues')
- #@new_resource.values([{:name=>"DontExist", :type=>:string, :data=>"These will be ignored anyways"}])
+ # @new_resource.values([{:name=>"DontExist", :type=>:string, :data=>"These will be ignored anyways"}])
@new_resource.recursive(true)
@new_resource.run_action(:delete_key)
end
@@ -645,9 +645,9 @@ 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_parent + '\ReportKey')
- #Not testing for before or after values to match since
- #after -> new_resource.values and
- #before -> current_resource.values
+ # Not testing for before or after values to match since
+ # after -> new_resource.values and
+ # before -> current_resource.values
expect(@report["resources"][0]["result"]).to eq("delete_key")
expect(@report["status"]).to eq("success")
expect(@report["total_res_count"]).to eq("1")
@@ -659,13 +659,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_file_spec.rb b/spec/functional/resource/remote_file_spec.rb
index 94c42a73ba..a121cbb1f3 100644
--- a/spec/functional/resource/remote_file_spec.rb
+++ b/spec/functional/resource/remote_file_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Seth Chisamore (<schisamo@chef.io>)
-# Copyright:: Copyright 2011-2016, Chef Software Inc.
+# Copyright:: Copyright 2011-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,6 +28,9 @@ describe Chef::Resource::RemoteFile do
before(:each) do
@old_file_cache = Chef::Config[:file_cache_path]
Chef::Config[:file_cache_path] = file_cache_path
+ Chef::Config[:rest_timeout] = 2
+ Chef::Config[:http_retry_delay] = 0
+ Chef::Config[:http_retry_count] = 0
end
after(:each) do
@@ -55,11 +58,11 @@ describe Chef::Resource::RemoteFile do
let(:default_mode) { (0666 & ~File.umask).to_s(8) }
context "when fetching files over HTTP" do
- before(:each) do
- start_tiny_server
+ before(:all) do
+ start_tiny_server(RequestTimeout: 1)
end
- after(:each) do
+ after(:all) do
stop_tiny_server
end
@@ -97,21 +100,22 @@ describe Chef::Resource::RemoteFile do
context "when fetching files over HTTPS" do
- before(:each) 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)
key_text = File.read(File.expand_path("ssl/chef-rspec.key", CHEF_SPEC_DATA))
key = OpenSSL::PKey::RSA.new(key_text)
- server_opts = { :SSLEnable => true,
- :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
- :SSLCertificate => cert,
- :SSLPrivateKey => key }
+ server_opts = { SSLEnable: true,
+ SSLVerifyClient: OpenSSL::SSL::VERIFY_NONE,
+ SSLCertificate: cert,
+ SSLPrivateKey: key,
+ RequestTimeout: 1 }
start_tiny_server(server_opts)
end
- after(:each) do
+ after(:all) do
stop_tiny_server
end
@@ -295,11 +299,11 @@ describe Chef::Resource::RemoteFile do
end
context "when dealing with content length checking" do
- before(:each) do
- start_tiny_server
+ before(:all) do
+ start_tiny_server(RequestTimeout: 1)
end
- after(:each) do
+ after(:all) do
stop_tiny_server
end
@@ -356,7 +360,7 @@ describe Chef::Resource::RemoteFile do
it "should raise ContentLengthMismatch" do
expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::ContentLengthMismatch)
- #File.should_not exist(path) # XXX: CHEF-5081
+ # File.should_not exist(path) # XXX: CHEF-5081
end
end
@@ -369,7 +373,7 @@ describe Chef::Resource::RemoteFile do
it "should raise ContentLengthMismatch" do
expect { resource.run_action(:create) }.to raise_error(Chef::Exceptions::ContentLengthMismatch)
- #File.should_not exist(path) # XXX: CHEF-5081
+ # File.should_not exist(path) # XXX: CHEF-5081
end
end
diff --git a/spec/functional/resource/rpm_spec.rb b/spec/functional/resource/rpm_spec.rb
index 17d0bf9e3c..fcaf8817eb 100644
--- a/spec/functional/resource/rpm_spec.rb
+++ b/spec/functional/resource/rpm_spec.rb
@@ -22,7 +22,7 @@ require "chef/mixin/shell_out"
# run this test only for following platforms.
exclude_test = !%w{aix rhel fedora suse}.include?(ohai[:platform_family])
-describe Chef::Resource::RpmPackage, :requires_root, :external => exclude_test do
+describe Chef::Resource::RpmPackage, :requires_root, external: exclude_test do
include Chef::Mixin::ShellOut
let(:new_resource) do
diff --git a/spec/functional/resource/template_spec.rb b/spec/functional/resource/template_spec.rb
index b9a39255f4..679ffe661a 100644
--- a/spec/functional/resource/template_spec.rb
+++ b/spec/functional/resource/template_spec.rb
@@ -68,7 +68,7 @@ describe Chef::Resource::Template do
context "when the target file does not exist" do
it "creates the template with the rendered content using the variable attribute when the :create action is run" do
resource.source("openldap_variable_stuff.conf.erb")
- resource.variables(:secret => "nutella")
+ resource.variables(secret: "nutella")
resource.run_action(:create)
expect(IO.read(path)).to eq("super secret is nutella")
end
@@ -112,7 +112,7 @@ describe Chef::Resource::Template do
context "using single helper syntax referencing @node" do
before do
node.normal[:helper_test_attr] = "value from helper method"
- resource.helper(:helper_method) { "#{@node[:helper_test_attr]}" }
+ resource.helper(:helper_method) { (@node[:helper_test_attr]).to_s }
end
it_behaves_like "a template with helpers"
@@ -213,21 +213,21 @@ describe Chef::Resource::Template do
describe "when template variables contain lazy{} calls" do
it "resolves the DelayedEvaluator" do
resource.source("openldap_variable_stuff.conf.erb")
- resource.variables(:secret => Chef::DelayedEvaluator.new { "nutella" })
+ resource.variables(secret: Chef::DelayedEvaluator.new { "nutella" })
resource.run_action(:create)
expect(IO.read(path)).to eq("super secret is nutella")
end
it "does not mutate the resource variables" do
resource.source("openldap_variable_stuff.conf.erb")
- resource.variables(:secret => Chef::DelayedEvaluator.new { "nutella" })
+ resource.variables(secret: Chef::DelayedEvaluator.new { "nutella" })
resource.run_action(:create)
expect(resource.variables[:secret]).to be_a Chef::DelayedEvaluator
end
it "resolves the DelayedEvaluator when deeply nested" do
resource.source("openldap_nested_variable_stuff.erb")
- resource.variables(:secret => [{ "key" => Chef::DelayedEvaluator.new { "nutella" } }])
+ resource.variables(secret: [{ "key" => Chef::DelayedEvaluator.new { "nutella" } }])
resource.run_action(:create)
expect(IO.read(path)).to eq("super secret is nutella")
end
diff --git a/spec/functional/resource/user/dscl_spec.rb b/spec/functional/resource/user/dscl_spec.rb
index ed96e31bac..78d7f2336e 100644
--- a/spec/functional/resource/user/dscl_spec.rb
+++ b/spec/functional/resource/user/dscl_spec.rb
@@ -19,9 +19,9 @@ require "spec_helper"
require "chef/mixin/shell_out"
metadata = {
- :mac_osx_only => true,
- :requires_root => true,
- :not_supported_on_mac_osx_106 => true,
+ mac_osx_only: true,
+ requires_root: true,
+ not_supported_on_mac_osx_106: true,
}
describe "Chef::Resource::User with Chef::Provider::User::Dscl provider", metadata do
diff --git a/spec/functional/resource/user/useradd_spec.rb b/spec/functional/resource/user/useradd_spec.rb
deleted file mode 100644
index e783356c9f..0000000000
--- a/spec/functional/resource/user/useradd_spec.rb
+++ /dev/null
@@ -1,709 +0,0 @@
-# encoding: UTF-8
-#
-# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2013-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-require "functional/resource/base"
-require "chef/mixin/shell_out"
-
-def resource_for_platform(username, run_context)
- Chef::Resource.resource_for_node(:user, node).new(username, run_context)
-end
-
-# ideally we could somehow pass an array of [ ...::Aix, ...::Linux ] to the
-# filter, but we have to pick the right one for the O/S.
-def user_provider_filter
- case ohai[:os]
- when "aix"
- Chef::Provider::User::Aix
- when "linux"
- Chef::Provider::User::Linux
- end
-end
-
-metadata = {
- :unix_only => true,
- :requires_root => true,
- :not_supported_on_mac_osx => true,
- :provider => { :user => user_provider_filter },
-}
-
-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 }
- matcher = /^#{Regexp.escape(username)}.+$/
- if passwd_entry = passwd_file.scan(matcher).first
- PwEntry.new(*passwd_entry.split(":"))
- else
- raise UserNotFound, "no entry matching #{matcher.inspect} found in /etc/passwd"
- end
- end
-
- def etc_shadow
- case ohai[:platform]
- when "aix"
- File.open("/etc/security/passwd") { |f| f.read }
- else
- File.open("/etc/shadow") { |f| f.read }
- end
- end
-
- def self.quote_in_username_unsupported?
- if OHAI_SYSTEM["platform_family"] == "debian"
- false
- else
- "Only debian family systems support quotes in username"
- end
- end
-
- def password_should_be_set
- if ohai[:platform] == "aix"
- expect(pw_entry.passwd).to eq("!")
- else
- expect(pw_entry.passwd).to eq("x")
- end
- end
-
- def try_cleanup
- ["/home/cheftestfoo", "/home/cheftestbar", "/home/cf-test"].each do |f|
- FileUtils.rm_rf(f) if File.exists? f
- end
-
- ["cf-test"].each do |u|
- r = resource_for_platform("DELETE USER", run_context)
- r.manage_home true
- r.username("cf-test")
- r.run_action(:remove)
- end
- end
-
- before do
- # Silence shell_out live stream
- Chef::Log.level = :warn
- try_cleanup
- end
-
- after do
- max_retries = 3
- 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])
-
- # 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.
- # The work around is to retry userdel for 3 times.
- break if status.exitstatus != 8
-
- sleep 1
- max_retries -= 1
- rescue UserNotFound
- break
- end
- end
-
- status.error! if max_retries == 0
- end
-
- let(:node) do
- n = Chef::Node.new
- n.consume_external_attrs(OHAI_SYSTEM.data.dup, {})
- n
- end
-
- let(:events) do
- Chef::EventDispatch::Dispatcher.new
- end
-
- let(:run_context) do
- Chef::RunContext.new(node, {}, events)
- end
-
- let(:username) { "cf-test" }
- let(:uid) { nil }
- let(:home) { nil }
- let(:manage_home) { false }
- let(:password) { nil }
- let(:system) { false }
- let(:comment) { nil }
-
- let(:user_resource) do
- r = resource_for_platform("TEST USER RESOURCE", run_context)
- r.username(username)
- r.uid(uid)
- r.home(home)
- r.comment(comment)
- r.manage_home(manage_home)
- r.password(password)
- r.system(system)
- r
- end
-
- let(:expected_shadow) do
- if ohai[:platform] == "aix"
- 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
-
- # On Debian, the only constraints are that usernames must neither start
- # with a dash ('-') nor plus ('+') nor tilde ('~') nor contain a colon
- # (':'), a comma (','), or a whitespace (space: ' ', end of line: '\n',
- # tabulation: '\t', etc.). Note that using a slash ('/') may break the
- # 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
- expect(pw_entry.name).to eq(username)
- end
- end
-
- context "when uid is set" do
- # Should verify uid not in use...
- let(:uid) { 1999 }
-
- it "ensures the user has the given uid" do
- expect(pw_entry.uid).to eq("1999")
- end
- end
-
- context "when comment is set" do
- let(:comment) { "hello this is dog" }
-
- it "ensures the comment is set" do
- expect(pw_entry.gecos).to eq("hello this is dog")
- end
-
- context "in standard gecos format" do
- let(:comment) { "Bobo T. Clown,some building,555-555-5555,@boboclown" }
-
- it "ensures the comment is set" do
- expect(pw_entry.gecos).to eq(comment)
- end
- end
-
- context "to a string containing multibyte characters" do
- let(:comment) { "(╯°□°)╯︵ ┻━┻" }
-
- it "ensures the comment is set" do
- actual = pw_entry.gecos
- actual.force_encoding(Encoding::UTF_8) if "".respond_to?(:force_encoding)
- expect(actual).to eq(comment)
- end
- end
-
- context "to a string containing an apostrophe `'`" do
- let(:comment) { "don't go" }
-
- it "ensures the comment is set" do
- expect(pw_entry.gecos).to eq(comment)
- end
- end
- end
-
- context "when home is set" do
- let(:home) { "/home/#{username}" }
-
- it "ensures the user's home is set to the given path" do
- expect(pw_entry.home).to eq(home)
- end
-
- it "does not create the home dir without `manage_home'" do
- expect(File).not_to exist(home)
- end
-
- context "and manage_home is enabled" do
- let(:manage_home) { true }
-
- it "ensures the user's home directory exists" do
- expect(File).to exist(home)
- end
- end
-
- context "and manage_home is the default" do
- let(:manage_home) { nil }
-
- it "does not create the home dir without `manage_home'" do
- expect(File).not_to exist(home)
- end
- end
- end
-
- context "when a password is specified" do
- # openssl passwd -1 "secretpassword"
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- it "sets the user's shadow password" do
- password_should_be_set
- expect(etc_shadow).to include(expected_shadow)
- end
- end
-
- context "when a system user is specified", skip: aix? do
- let(:system) { true }
- let(:uid_min) do
- # from `man useradd`, login user means uid will be between
- # UID_SYS_MIN and UID_SYS_MAX defined in /etc/login.defs. On my
- # 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 }
- uid_min_scan = /^UID_MIN\s+(\d+)/
- login_defs.match(uid_min_scan)[1]
- end
-
- it "ensures the user has the properties of a system user" do
- expect(pw_entry.uid.to_i).to be < uid_min.to_i
- end
- end
- end # when the user does not exist beforehand
-
- context "when the user already exists" do
-
- let(:expect_updated?) { true }
-
- let(:existing_uid) { nil }
- let(:existing_home) { nil }
- let(:existing_manage_home) { false }
- let(:existing_password) { nil }
- let(:existing_system) { false }
- let(:existing_comment) { nil }
-
- let(:existing_user) do
- r = resource_for_platform("TEST USER RESOURCE", run_context)
- # username is identity attr, must match.
- r.username(username)
- r.uid(existing_uid)
- r.home(existing_home)
- r.comment(existing_comment)
- r.manage_home(existing_manage_home)
- r.password(existing_password)
- r.system(existing_system)
- r
- end
-
- before do
- if reason = skip
- skip(reason)
- end
- existing_user.run_action(:create)
- expect(existing_user).to be_updated_by_last_action
- user_resource.run_action(:create)
- expect(user_resource.updated_by_last_action?).to eq(expect_updated?)
- end
-
- context "and all properties are in the desired state" do
- let(:uid) { 1999 }
- let(:home) { "/home/bobo" }
- let(:manage_home) { true }
- # openssl passwd -1 "secretpassword"
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- let(:system) { false }
- let(:comment) { "hello this is dog" }
-
- let(:existing_uid) { uid }
- let(:existing_home) { home }
- let(:existing_manage_home) { manage_home }
- let(:existing_password) { password }
- let(:existing_system) { false }
- let(:existing_comment) { comment }
-
- let(:expect_updated?) { false }
-
- it "does not update the user" do
- expect(user_resource).not_to be_updated
- end
- end
-
- context "and the uid is updated" do
- let(:uid) { 1999 }
- let(:existing_uid) { 1998 }
-
- it "ensures the uid is set to the desired value" do
- expect(pw_entry.uid).to eq("1999")
- end
- end
-
- context "and the comment is updated" do
- let(:comment) { "hello this is dog" }
- let(:existing_comment) { "woof" }
-
- it "ensures the comment field is set to the desired value" do
- expect(pw_entry.gecos).to eq("hello this is dog")
- end
- end
-
- context "and home directory is updated" do
- let(:existing_home) { "/home/cheftestfoo" }
- let(:home) { "/home/cheftestbar" }
- it "ensures the home directory is set to the desired value" do
- expect(pw_entry.home).to eq("/home/cheftestbar")
- end
-
- context "and manage_home is enabled" do
- let(:existing_manage_home) { true }
- let(:manage_home) { true }
- it "moves the home directory to the new location" do
- expect(File).not_to exist("/home/cheftestfoo")
- expect(File).to exist("/home/cheftestbar")
- end
- end
-
- context "and manage_home wasn't enabled but is now" do
- let(:existing_manage_home) { false }
- let(:manage_home) { true }
-
- if %w{rhel fedora}.include?(OHAI_SYSTEM["platform_family"])
- # Inconsistent behavior. See: CHEF-2205
- it "created the home dir b/c of CHEF-2205 so it still exists" do
- # This behavior seems contrary to expectation and non-convergent.
- expect(File).not_to exist("/home/cheftestfoo")
- expect(File).to exist("/home/cheftestbar")
- end
- elsif ohai[:platform] == "aix"
- it "creates the home dir in the desired location" do
- expect(File).not_to exist("/home/cheftestfoo")
- expect(File).to exist("/home/cheftestbar")
- end
- else
- it "does not create the home dir in the desired location (XXX)" do
- # This behavior seems contrary to expectation and non-convergent.
- expect(File).not_to exist("/home/cheftestfoo")
- expect(File).not_to exist("/home/cheftestbar")
- end
- end
- end
-
- context "and manage_home was enabled but is not now" do
- let(:existing_manage_home) { true }
- let(:manage_home) { false }
-
- it "leaves the old home directory around (XXX)" do
- # Would it be better to remove the old home?
- expect(File).to exist("/home/cheftestfoo")
- expect(File).not_to exist("/home/cheftestbar")
- end
- end
- end
-
- context "and a password is added" do
- # openssl passwd -1 "secretpassword"
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- 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
- # openssl passwd -1 "OLDpassword"
- let(:existing_password) do
- case ohai[:platform]
- when "aix"
- "jkzG6MvUxjk2g"
- else
- "$1$1dVmwm4z$CftsFn8eBDjDRUytYKkXB."
- end
- end
-
- # openssl passwd -1 "secretpassword"
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- it "ensures the password is set to the desired value" do
- password_should_be_set
- expect(etc_shadow).to include(expected_shadow)
- end
- end
-
- context "and the user is changed from not-system to system" do
- let(:existing_system) { false }
- let(:system) { true }
-
- let(:expect_updated?) { false }
-
- it "does not modify the user at all" do
- end
- end
-
- context "and the user is changed from system to not-system" do
- let(:existing_system) { true }
- let(:system) { false }
-
- let(:expect_updated?) { false }
-
- it "does not modify the user at all" do
- end
- end
-
- end # when the user already exists
- end # action :create
-
- shared_context "user exists for lock/unlock" do
- let(:user_locked_context?) { false }
-
- def shadow_entry
- etc_shadow.lines.find { |l| l.include?(username) }
- end
-
- def shadow_password
- shadow_entry.split(":")[1]
- end
-
- def aix_user_lock_status
- lock_info = shell_out!("lsuser -a account_locked #{username}")
- /\S+\s+account_locked=(\S+)/.match(lock_info.stdout)[1]
- end
-
- def user_account_should_be_locked
- case ohai[:platform]
- when "aix"
- expect(aix_user_lock_status).to eq("true")
- else
- expect(shadow_password).to include("!")
- end
- end
-
- def user_account_should_be_unlocked
- case ohai[:platform]
- when "aix"
- expect(aix_user_lock_status).to eq("false")
- else
- expect(shadow_password).not_to include("!")
- end
- end
-
- def lock_user_account
- case ohai[:platform]
- when "aix"
- shell_out!("chuser account_locked=true #{username}")
- else
- shell_out!("usermod -L #{username}")
- end
- end
-
- before do
- # create user and setup locked/unlocked state
- user_resource.dup.run_action(:create)
-
- if user_locked_context?
- lock_user_account
- user_account_should_be_locked
- elsif password
- user_account_should_be_unlocked
- end
- end
- end
-
- describe "action :lock" do
- context "when the user does not exist" do
- it "raises a sensible error" do
- expect { user_resource.run_action(:lock) }.to raise_error(Chef::Exceptions::User)
- end
- end
-
- context "when the user exists" do
-
- include_context "user exists for lock/unlock"
-
- before do
- user_resource.run_action(:lock)
- end
-
- context "and the user is not locked" do
- # user will be locked if it has no password
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- it "locks the user's password" do
- user_account_should_be_locked
- end
- end
-
- context "and the user is locked" do
- # user will be locked if it has no password
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- let(:user_locked_context?) { true }
- it "does not update the user" do
- expect(user_resource).not_to be_updated_by_last_action
- end
- end
- end
- end # action :lock
-
- describe "action :unlock" do
- context "when the user does not exist" do
- it "raises a sensible error" do
- expect { user_resource.run_action(:unlock) }.to raise_error(Chef::Exceptions::User)
- end
- end
-
- context "when the user exists" do
-
- include_context "user exists for lock/unlock"
-
- before do
- begin
- user_resource.run_action(:unlock)
- @error = nil
- rescue Exception => e
- @error = e
- end
- end
-
- context "and has no password" do
-
- # TODO: platform_family should be setup in spec_helper w/ tags
- if %w{opensuse}.include?(OHAI_SYSTEM["platform_family"]) ||
- (%w{suse}.include?(OHAI_SYSTEM["platform_family"]) &&
- OHAI_SYSTEM["platform_version"].to_f < 12.0)
- # suse 11.x gets this right:
- it "errors out trying to unlock the user" do
- expect(@error).to be_a(Mixlib::ShellOut::ShellCommandFailed)
- expect(@error.message).to include("Cannot unlock the password")
- end
- elsif %w{rhel}.include?(OHAI_SYSTEM["platform_family"]) &&
- OHAI_SYSTEM["platform_version"].to_f == 6.8
- # usermod -U returns following message for rhel68 on s390x platforms
- # usermod: unlocking the user's password would result in a passwordless account.
- #You should set a password with usermod -p to unlock this user's password.
- it "errors out trying to unlock the user" do
- expect(@error).to be_a(Mixlib::ShellOut::ShellCommandFailed)
- expect(@error.message).to include("You should set a password")
- end
- else
-
- # borked on all other platforms:
- it "is marked as updated but doesn't modify the user (XXX)" do
- # This should be an error instead; note that usermod still exits 0
- # (which is probably why this case silently fails):
- #
- # DEBUG: ---- Begin output of usermod -U chef-functional-test ----
- # DEBUG: STDOUT:
- # DEBUG: STDERR: usermod: unlocking the user's password would result in a passwordless account.
- # You should set a password with usermod -p to unlock this user's password.
- # DEBUG: ---- End output of usermod -U chef-functional-test ----
- # DEBUG: Ran usermod -U chef-functional-test returned 0
- expect(@error).to be_nil
- if ohai[:platform] == "aix"
- expect(pw_entry.passwd).to eq("*")
- user_account_should_be_unlocked
- else
- expect(pw_entry.passwd).to eq("x")
- expect(shadow_password).to include("!")
- end
- end
- end
- end
-
- context "and has a password" do
- let(:password) do
- case ohai[:platform]
- when "aix"
- "eL5qfEVznSNss"
- else
- "$1$RRa/wMM/$XltKfoX5ffnexVF4dHZZf/"
- end
- end
-
- context "and the user is not locked" do
- it "does not update the user" do
- expect(user_resource).not_to be_updated_by_last_action
- end
- end
-
- context "and the user is locked" do
- let(:user_locked_context?) { true }
-
- it "unlocks the user's password" do
- user_account_should_be_unlocked
- end
- end
- end
- end
- end # action :unlock
-
-end
diff --git a/spec/functional/resource/user/windows_spec.rb b/spec/functional/resource/user/windows_spec.rb
index f61a51c636..56ae962ee4 100644
--- a/spec/functional/resource/user/windows_spec.rb
+++ b/spec/functional/resource/user/windows_spec.rb
@@ -31,6 +31,7 @@ describe Chef::Provider::User::Windows, :windows_only do
end
let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
let(:new_resource) do
Chef::Resource::User.new(username, run_context).tap do |r|
@@ -45,6 +46,7 @@ describe Chef::Provider::User::Windows, :windows_only do
before do
delete_user(username)
+ allow(run_context).to receive(:logger).and_return(logger)
end
describe "action :create" do
@@ -69,7 +71,7 @@ describe Chef::Provider::User::Windows, :windows_only do
context "with a gid specified" do
it "warns unsupported" do
- expect(Chef::Log).to receive(:warn).with(/not implemented/)
+ expect(logger).to receive(:warn).with(/not implemented/)
new_resource.gid("agroup")
new_resource.run_action(:create)
end
diff --git a/spec/functional/resource/windows_env_spec.rb b/spec/functional/resource/windows_env_spec.rb
new file mode 100644
index 0000000000..e5f2032795
--- /dev/null
+++ b/spec/functional/resource/windows_env_spec.rb
@@ -0,0 +1,285 @@
+#
+# Author:: Adam Edwards (<adamed@chef.io>)
+# Copyright:: Copyright 2014-2016, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsEnv, :windows_only do
+ context "when running on Windows" do
+ let(:chef_env_test_lower_case) { "chefenvtest" }
+ let(:chef_env_test_mixed_case) { "chefENVtest" }
+ let(:chef_env_with_delim) { "chef_env_with_delim" }
+ let(:chef_env_delim) { ";" }
+ let(:chef_env_test_delim) { "#{value1};#{value2}" }
+ let(:env_dne_key) { "env_dne_key" }
+ let(:env_value1) { "value1" }
+ let(:env_value2) { "value2" }
+ let(:delim_value) { "#{env_value1};#{env_value2}" }
+ let(:env_user) { ENV["USERNAME"].upcase }
+ let(:default_env_user) { "<SYSTEM>" }
+
+ let(:env_obj) do
+ wmi = WmiLite::Wmi.new
+ environment_variables = wmi.query("select * from Win32_Environment where name = '#{test_resource.key_name}'")
+ if environment_variables && environment_variables.length > 0
+ environment_variables.each do |env|
+ env_obj = env.wmi_ole_object
+ return env_obj if env_obj.username.split('\\').last.casecmp(test_resource.user) == 0
+ end
+ end
+ nil
+ end
+
+ let(:env_value_expandable) { "%SystemRoot%" }
+ let(:test_run_context) do
+ node = Chef::Node.new
+ node.default["os"] = "windows"
+ node.default["platform"] = "windows"
+ node.default["platform_version"] = "6.1"
+ empty_events = Chef::EventDispatch::Dispatcher.new
+ Chef::RunContext.new(node, {}, empty_events)
+ end
+ let(:test_resource) do
+ Chef::Resource::WindowsEnv.new("unknown", test_run_context)
+ end
+
+ before(:each) do
+ resource_lower = Chef::Resource::WindowsEnv.new(chef_env_test_lower_case, test_run_context)
+ resource_lower.run_action(:delete)
+ resource_lower = Chef::Resource::WindowsEnv.new(chef_env_test_lower_case, test_run_context)
+ resource_lower.user(env_user)
+ resource_lower.run_action(:delete)
+ resource_mixed = Chef::Resource::WindowsEnv.new(chef_env_test_mixed_case, test_run_context)
+ resource_mixed.run_action(:delete)
+ resource_mixed = Chef::Resource::WindowsEnv.new(chef_env_test_mixed_case, test_run_context)
+ resource_lower.user(env_user)
+ resource_mixed.run_action(:delete)
+ end
+
+ context "when the create action is invoked" do
+ it "should create an environment variable for action create" 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)
+ test_resource.run_action(:create)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ end
+
+ it "should create an environment variable with default user System for action create" 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)
+ test_resource.run_action(:create)
+ expect(env_obj.username.upcase).to eq(default_env_user)
+ end
+
+ it "should create an environment variable with user for action create" 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)
+ test_resource.user(env_user)
+ test_resource.run_action(:create)
+ expect(env_obj.username.split('\\').last.upcase).to eq(env_user)
+ end
+
+ context "when env variable exist with same name" do
+ before(:each) do
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.value(env_value1)
+ test_resource.run_action(:create)
+ end
+ it "should modify an existing variable's value to a new value" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.value(env_value2)
+ test_resource.run_action(:create)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
+ end
+
+ it "should not modify an existing variable's value to a new value if the users are different" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.value(env_value2)
+ test_resource.user(env_user)
+ test_resource.run_action(:create)
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.user(default_env_user)
+ expect(env_obj.variablevalue).to eq(env_value1)
+ end
+
+ it "should modify an existing variable's value to a new value if the variable name case differs from the existing variable" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.key_name(chef_env_test_mixed_case)
+ test_resource.value(env_value2)
+ test_resource.run_action(:create)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
+ end
+ end
+
+ it "should not expand environment variables if the variable is not PATH" do
+ expect(ENV[chef_env_test_lower_case]).to eq(nil)
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.value(env_value_expandable)
+ test_resource.run_action(:create)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value_expandable)
+ end
+ end
+
+ context "when the modify action is invoked" do
+ it "should raise an exception for modify if the variable doesn't exist" 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::WindowsEnv)
+ end
+
+ context "when env variable exist with same name" do
+ before(:each) do
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.value(env_value1)
+ test_resource.run_action(:create)
+ end
+
+ it "should modify an existing variable's value to a new value" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.value(env_value2)
+ test_resource.run_action(:modify)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
+ end
+
+ # This examlpe covers Chef Issue #1754
+ it "should modify an existing variable's value to a new value if the variable name case differs from the existing variable" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.key_name(chef_env_test_mixed_case)
+ test_resource.value(env_value2)
+ test_resource.run_action(:modify)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value2)
+ end
+
+ it "should not expand environment variables if the variable is not PATH" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.value(env_value_expandable)
+ test_resource.run_action(:modify)
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value_expandable)
+ end
+ end
+
+ context "when using PATH" do
+ let(:random_name) { Time.now.to_i }
+ 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"] }
+
+ it "should expand PATH" do
+ expect(path_before).not_to include(env_val)
+ test_resource.key_name("PATH")
+ test_resource.value("#{path_before};#{env_val}")
+ test_resource.run_action(:create)
+ expect(ENV["PATH"]).not_to include(env_val)
+ expect(ENV["PATH"]).to include((random_name).to_s)
+ end
+
+ after(:each) do
+ # cleanup so we don't flood the path
+ test_resource.key_name("PATH")
+ test_resource.value(path_before)
+ test_resource.run_action(:create)
+ ENV["PATH"] = env_path_before
+ end
+ end
+
+ end
+
+ context "when the delete action is invoked" do
+ context "when env variable exist with same name" do
+ before(:each) do
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.value(env_value1)
+ test_resource.run_action(:create)
+ end
+
+ it "should delete a System environment variable" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.run_action(:delete)
+ expect(ENV[chef_env_test_lower_case]).to eq(nil)
+ end
+
+ it "should not delete an System environment variable if user are passed" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.user(env_user)
+ test_resource.run_action(:delete)
+ test_resource.user(default_env_user)
+ expect(env_obj).not_to be_nil
+ end
+ end
+
+ context "when env variable exist with same name" do
+ before(:each) do
+ test_resource.key_name(chef_env_test_lower_case)
+ test_resource.value(env_value1)
+ test_resource.user(env_user)
+ test_resource.run_action(:create)
+ end
+
+ it "should delete a user environment variable" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.run_action(:delete)
+ expect(env_obj).to eq(nil)
+ end
+
+ it "should not delete an user environment variable if user is not passed" do
+ expect(ENV[chef_env_test_lower_case]).to eq(env_value1)
+ test_resource.user(default_env_user)
+ test_resource.run_action(:delete)
+ test_resource.user(env_user)
+ expect(env_obj).not_to be_nil
+ end
+ end
+
+ context "when env variable exist with same name" do
+ before(:each) do
+ test_resource.key_name(chef_env_with_delim)
+ test_resource.delim(chef_env_delim)
+ test_resource.value(delim_value)
+ test_resource.run_action(:create)
+ end
+
+ it "should not delete variable when a delim present" do
+ expect(ENV[chef_env_with_delim]).to eq(delim_value)
+ test_resource.value(env_value1)
+ test_resource.run_action(:delete)
+ expect(ENV[chef_env_with_delim]).to eq(env_value2)
+ end
+ end
+
+ it "should not raise an exception when a non-existent environment variable is deleted" 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(ENV[chef_env_test_lower_case]).to eq(nil)
+ end
+
+ it "should delete a value from the current process even if it is not in the registry" do
+ expect(ENV[env_dne_key]).to eq(nil)
+ ENV[env_dne_key] = env_value1
+ test_resource.key_name(env_dne_key)
+ test_resource.run_action(:delete)
+ expect(ENV[env_dne_key]).to eq(nil)
+ end
+
+ end
+ end
+end
diff --git a/spec/functional/resource/windows_service_spec.rb b/spec/functional/resource/windows_service_spec.rb
index 531f9e9250..f422ac21d6 100644
--- a/spec/functional/resource/windows_service_spec.rb
+++ b/spec/functional/resource/windows_service_spec.rb
@@ -18,7 +18,7 @@
require "spec_helper"
-describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_gem_only, :appveyor_only, :broken => true do
+describe Chef::Resource::WindowsService, :windows_only, :system_windows_service_gem_only, :appveyor_only, broken: true do
# Marking as broken. This test is causing appveyor tests to exit with 116.
include_context "using Win32::Service"
diff --git a/spec/functional/resource/windows_task_spec.rb b/spec/functional/resource/windows_task_spec.rb
index fbb5e4dd12..05f46d20ce 100644
--- a/spec/functional/resource/windows_task_spec.rb
+++ b/spec/functional/resource/windows_task_spec.rb
@@ -20,7 +20,8 @@ require "spec_helper"
require "chef/provider/windows_task"
describe Chef::Resource::WindowsTask, :windows_only do
- let(:task_name) { "chef-client" }
+ # resource.task.application_name will default to task_name unless resource.command is set
+ let(:task_name) { "chef-client-functional-test" }
let(:new_resource) { Chef::Resource::WindowsTask.new(task_name) }
let(:windows_task_provider) do
node = Chef::Node.new
@@ -31,20 +32,119 @@ describe Chef::Resource::WindowsTask, :windows_only do
describe "action :create" do
after { delete_task }
+ context "when command is with arguments" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ # Make sure MM/DD/YYYY is accepted
+
+ new_resource.start_day "09/20/2017"
+ new_resource.frequency :hourly
+ new_resource
+ end
+
+ it "creates scheduled task and sets command arguments" do
+ subject.command "chef-client -W"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq("chef-client")
+ expect(current_resource.task.parameters).to eq("-W")
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.command "chef-client -W"
+ subject.run_action(:create)
+ subject.command "chef-client -W"
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates scheduled task and sets command arguments" do
+ subject.command "chef-client -W -L 'C:\\chef\\chef-ad-join.log'"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq("chef-client")
+ expect(current_resource.task.parameters).to eq("-W -L C:\\\\chef\\\\chef-ad-join.log")
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.command "chef-client -W -L 'C:\\chef\\chef-ad-join.log'"
+ subject.run_action(:create)
+ subject.command "chef-client -W -L 'C:\\chef\\chef-ad-join.log'"
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates scheduled task and sets command arguments" do
+ subject.command '"C:\\Program Files\\example\program.exe" -arg1 --arg2'
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq("C:\\Program Files\\example\\program.exe")
+ expect(current_resource.task.parameters).to eq("-arg1 --arg2")
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.command '"C:\\Program Files\\example\program.exe" -arg1 --arg2'
+ subject.run_action(:create)
+ subject.command '"C:\\Program Files\\example\program.exe" -arg1 --arg2'
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates scheduled task and sets command arguments" do
+ subject.command "ping http://www.google.com"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq("ping")
+ expect(current_resource.task.parameters).to eq("http://www.google.com")
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.command "ping http://www.google.com"
+ subject.run_action(:create)
+ subject.command "ping http://www.google.com"
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
- context "when frequency and frequency_modifier are not passed" do
+ context "when frequency_modifier are not passed" do
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ # Make sure MM/DD/YYYY is accepted
+ new_resource.start_day "09/20/2017"
+ new_resource.frequency :hourly
new_resource
end
- it "creates a scheduled task to run every 1 hr" do
+ it "creates a scheduled task to run every 1 hr starting on 09/20/2017" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq(task_name)
+ trigger_details = current_resource.task.trigger(0)
+ expect(trigger_details[:start_year]).to eq("2017")
+ expect(trigger_details[:start_month]).to eq("09")
+ expect(trigger_details[:start_day]).to eq("20")
+ expect(trigger_details[:minutes_interval]).to eq(60)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:"Repeat:Every"]).to eq("1 Hour(s), 0 Minute(s)")
+ expect(subject).not_to be_updated_by_last_action
end
end
@@ -55,16 +155,44 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.run_level :highest
new_resource.frequency :minute
new_resource.frequency_modifier 15
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "creates a scheduled task that runs after every 15 minutes" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:minutes_interval]).to eq(15)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:"Repeat:Every"]).to eq("0 Hour(s), 15 Minute(s)")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "updates a scheduled task when frequency_modifier updated to 20" do
+ subject.run_action(:create)
+ current_resource = call_for_load_current_resource
+ trigger_details = current_resource.task.trigger(0)
+ expect(trigger_details[:minutes_interval]).to eq(15)
+ subject.frequency_modifier 20
+ subject.run_action(:create)
+ expect(subject).to be_updated_by_last_action
+ # #loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:minutes_interval]).to eq(20)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
end
end
@@ -75,16 +203,42 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.run_level :highest
new_resource.frequency :hourly
new_resource.frequency_modifier 3
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "creates a scheduled task that runs after every 3 hrs" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:minutes_interval]).to eq(180)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:"Repeat:Every"]).to eq("3 Hour(s), 0 Minute(s)")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "updates a scheduled task to run every 5 hrs when frequency modifer updated to 5" do
+ subject.run_action(:create)
+ current_resource = call_for_load_current_resource
+ trigger_details = current_resource.task.trigger(0)
+ expect(trigger_details[:minutes_interval]).to eq(180)
+ # updating frequency modifer to 5 from 3
+ subject.frequency_modifier 5
+ subject.run_action(:create)
+ expect(subject).to be_updated_by_last_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:minutes_interval]).to eq(300)
+ expect(trigger_details[:trigger_type]).to eq(1)
end
end
@@ -94,66 +248,487 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :daily
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "creates a scheduled task to run daily" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(2)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days_interval]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("Daily")
- expect(task_details[:Days]).to eq("Every 1 day(s)")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
end
end
- context "frequency :monthly" do
+ describe "frequency :monthly" do
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :monthly
- new_resource.frequency_modifier 2
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
- it "creates a scheduled task to every 2 months" do
- subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("Monthly")
- expect(task_details[:Months]).to eq("FEB, APR, JUN, AUG, OCT, DEC")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ context "with start_day and start_time" do
+ before do
+ subject.start_day "02/12/2018"
+ subject.start_time "05:15"
+ end
+
+ it "if day property is not set creates a scheduled task to run monthly on first day of the month" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(1)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on first, second and third day of the month" do
+ subject.day "1, 2, 3"
+ call_for_create_action
+ # loading current resource again to check new task is created and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(7)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "1, 2, 3"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on 1, 2, 3, 4, 8, 20, 21, 15, 28, 31 day of the month" do
+ subject.day "1, 2, 3, 4, 8, 20, 21, 15, 28, 31"
+ call_for_create_action
+ # loading current resource again to check new task is created and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(1209548943) # TODO:: windows_task_provider.send(:days_of_month)
+ expect(trigger_details[:type][:months]).to eq(4095) # windows_task_provider.send(:months_of_year)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "1, 2, 3, 4, 8, 20, 21, 15, 28, 31"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on Jan, Feb, Apr, Dec on 1st 2nd 3rd 4th 8th and 20th day of these months" do
+ subject.day "1, 2, 3, 4, 8, 20, 21, 30"
+ subject.months "Jan, Feb, May, Sep, Dec"
+ call_for_create_action
+ # loading current resource again to check new task is created and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(538443919) # TODO:windows_task_provider.send(:days_of_month)
+ expect(trigger_details[:type][:months]).to eq(2323) # windows_task_provider.send(:months_of_year)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "1, 2, 3, 4, 8, 20, 21, 30"
+ subject.months "Jan, Feb, May, Sep, Dec"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly by giving day option with frequency_modifier" do
+ subject.frequency_modifier "First"
+ subject.day "Mon, Fri, Sun"
+ call_for_create_action
+ # loading current resource again to check new task is created and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(5)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days_of_week]).to eq(35)
+ expect(trigger_details[:type][:weeks_of_month]).to eq(1)
+ expect(trigger_details[:type][:months]).to eq(4095) # windows_task_provider.send(:months_of_year)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier "First"
+ subject.day "Mon, Fri, Sun"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "with frequency_modifier" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :monthly
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "raises argument error if frequency_modifier is 'first, second' and day is not provided." do
+ subject.frequency_modifier "first, second"
+ expect { subject.after_created }.to raise_error("Please select day on which you want to run the task e.g. 'Mon, Tue'. Multiple values must be seprated by comma.")
+ end
+
+ it "raises argument error if months is passed along with frequency_modifier" do
+ subject.frequency_modifier 3
+ subject.months "Jan, Mar"
+ expect { subject.after_created }.to raise_error("For frequency :monthly either use property months or frequency_modifier to set months.")
+ end
+
+ it "not raises any Argument error if frequency_modifier set as 'first, second, third' and day is provided" do
+ subject.frequency_modifier "first, second, third"
+ subject.day "Mon, Fri"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ end
+
+ it "not raises any Argument error if frequency_modifier 2 " do
+ subject.frequency_modifier 2
+ subject.day "Mon, Sun"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ end
+
+ it "raises argument error if frequency_modifier > 12" do
+ subject.frequency_modifier 13
+ expect { subject.after_created }.to raise_error("frequency_modifier value 13 is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
+ end
+
+ it "raises argument error if frequency_modifier < 1" do
+ subject.frequency_modifier 0
+ expect { subject.after_created }.to raise_error("frequency_modifier value 0 is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
+ end
+
+ it "creates scheduled task to run task monthly on Monday and Friday of first, second and thrid week of month" do
+ subject.frequency_modifier "first, second, third"
+ subject.day "Mon, Fri"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(5)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ expect(trigger_details[:type][:weeks_of_month]).to eq(7)
+ expect(trigger_details[:type][:days_of_week]).to eq(34)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier "first, second, third"
+ subject.day "Mon, Fri"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates scheduled task to run task monthly on every 6 months when frequency_modifier is 6 and to run on 1st and 2nd day of month" do
+ subject.frequency_modifier 6
+ subject.day "1, 2"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(trigger_details[:type][:months]).to eq(2080)
+ expect(trigger_details[:type][:days]).to eq(3)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier 6
+ subject.day "1, 2"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when day is set as last or lastday for frequency :monthly" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :monthly
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates scheduled task to run monthly to run last day of the month" do
+ subject.day "last"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ expect(trigger_details[:type][:days]).to eq(0)
+ expect(trigger_details[:run_on_last_day_of_month]).to eq(true)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "last"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "day property set as 'lastday' creates scheduled task to run monthly to run last day of the month" do
+ subject.day "lastday"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ expect(trigger_details[:type][:days]).to eq(0)
+ expect(trigger_details[:run_on_last_day_of_month]).to eq(true)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "lastday"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when frequency_modifier is set as last for frequency :monthly" do
+ it "creates scheduled task to run monthly on last week of the month" do
+ subject.frequency_modifier "last"
+ subject.day "Mon, Fri"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(5)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ expect(trigger_details[:type][:days_of_week]).to eq(34)
+ expect(trigger_details[:run_on_last_week_of_month]).to eq(true)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier "last"
+ subject.day "Mon, Fri"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when wild card (*) set as months" do
+ it "creates the scheduled task to run on 1st day of the all months" do
+ subject.months "*"
+ expect { subject.after_created }.not_to raise_error(ArgumentError)
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ expect(trigger_details[:type][:days]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.months "*"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when wild card (*) set as day" do
+ it "raises argument error" do
+ subject.day "*"
+ expect { subject.after_created }.to raise_error("day wild card (*) is only valid with frequency :weekly")
+ end
+ end
+
+ context "Pass either start day or start time by passing day compulsory or only pass frequency_modifier" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :monthly
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates a scheduled task to run monthly on second day of the month" do
+ subject.day "2"
+ subject.start_day "03/07/2018"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(2)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "2"
+ subject.start_day "03/07/2018"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on first, second and third day of the month" do
+ subject.day "1,2,3"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(7)
+ expect(trigger_details[:type][:months]).to eq(4095)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "1,2,3"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on each wednesday of the month" do
+ subject.frequency_modifier "1"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(1)
+ expect(trigger_details[:type][:months]).to eq(4095) # windows_task_provider.send(:months_of_year)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier "2"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "creates a scheduled task to run monthly on each wednesday of the month" do
+ subject.frequency_modifier "2"
+ subject.months = nil
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ # loading current resource
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(4)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:type][:days]).to eq(1)
+ expect(trigger_details[:type][:months]).to eq(2730) # windows_task_provider.send(:months_of_year)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency_modifier "2"
+ subject.months = nil
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
end
end
+ ## ToDO: Add functional specs to handle frequency monthly with frequency modifier set as 1-12
context "frequency :once" do
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :once
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
context "when start_time is not provided" do
it "raises argument error" do
- expect { subject.run_action(:create) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
+ expect { subject.after_created }.to raise_error("`start_time` needs to be provided with `frequency :once`")
end
end
context "when start_time is provided" do
it "creates the scheduled task to run once at 5pm" do
subject.start_time "17:00"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect("#{trigger_details[:start_hour]}:#{trigger_details[:start_minute]}" ).to eq(subject.start_time)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.start_time "17:00"
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("One Time Only")
- expect(task_details[:StartTime]).to eq("5:00:00 PM")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
end
end
end
@@ -164,45 +739,192 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :weekly
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "creates the scheduled task to run weekly" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(3)
+ expect(trigger_details[:type][:weeks_interval]).to eq(1)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("Weekly")
- expect(task_details[:Months]).to eq("Every 1 week(s)")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ context "when wild card (*) is set as day" do
+ it "creates hte scheduled task for all days of week" do
+ subject.day "*"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(3)
+ expect(trigger_details[:type][:weeks_interval]).to eq(1)
+ expect(trigger_details[:type][:days_of_week]).to eq(127)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "*"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
end
context "when days are provided" do
it "creates the scheduled task to run on particular days" do
subject.day "Mon, Fri"
subject.frequency_modifier 2
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(3)
+ expect(trigger_details[:type][:weeks_interval]).to eq(2)
+ expect(trigger_details[:type][:days_of_week]).to eq(34)
+ end
+
+ it "updates the scheduled task to run on if frequency_modifier is updated" do
+ subject.day "sun"
+ subject.frequency_modifier 2
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:Days]).to eq("MON, FRI")
- expect(task_details[:ScheduleType]).to eq("Weekly")
- expect(task_details[:Months]).to eq("Every 2 week(s)")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ current_resource = call_for_load_current_resource
+ trigger_details = current_resource.task.trigger(0)
+ expect(trigger_details[:type][:weeks_interval]).to eq(2)
+ expect(trigger_details[:type][:days_of_week]).to eq(1)
+ subject.day "Mon, Sun"
+ subject.frequency_modifier 3
+ # call for update
+ subject.run_action(:create)
+ expect(subject).to be_updated_by_last_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(3)
+ expect(trigger_details[:type][:weeks_interval]).to eq(3)
+ expect(trigger_details[:type][:days_of_week]).to eq(3)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.day "Mon, Fri"
+ subject.frequency_modifier 3
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when day property set as last" do
+ it "raises argument error" do
+ subject.day "last"
+ expect { subject.after_created }.to raise_error("day values 1-31 or last is only valid with frequency :monthly")
end
end
context "when invalid day is passed" do
it "raises error" do
subject.day "abc"
- expect { subject.run_action(:create) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
+ expect { subject.after_created }.to raise_error("day property invalid. Only valid values are: MON, TUE, WED, THU, FRI, SAT, SUN, *. Multiple values must be separated by a comma.")
end
end
context "when months are passed" do
it "raises error that months are supported only when frequency=:monthly" do
subject.months "Jan"
- expect { subject.run_action(:create) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
+ expect { subject.after_created }.to raise_error("months property is only valid for tasks that run monthly")
+ end
+ end
+
+ context "when start_day is not set" do
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "updates the day if start_day is not provided and user updates day property" do
+ skip "Unable to run this test case since start_day is current system date which can be different each time so can't verify the dynamic values"
+ subject.run_action(:create)
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(trigger_details[:type][:days_of_week]).to eq(8)
+ subject.day "Sat"
+ subject.run_action(:create)
+ # #loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(3)
+ expect(trigger_details[:type][:weeks_interval]).to eq(1)
+ expect(trigger_details[:type][:days_of_week]).to eq(64)
+ end
+ end
+ end
+
+ context "frequency :onstart" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :onstart
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates the scheduled task to run at system start up" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(8)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ context "when start_day and start_time is set" do
+ it "creates task to activate on '09/10/2018' at '15:00' when start_day = '09/10/2018' and start_time = '15:00' provided" do
+ subject.start_day "09/10/2018"
+ subject.start_time "15:00"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(8)
+ expect(trigger_details[:start_year]).to eq("2018")
+ expect(trigger_details[:start_month]).to eq("09")
+ expect(trigger_details[:start_day]).to eq("10")
+ expect(trigger_details[:start_hour]).to eq("15")
+ expect(trigger_details[:start_minute]).to eq("00")
end
end
end
@@ -213,16 +935,44 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :on_logon
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "creates the scheduled task to on logon" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(9)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("At logon time")
- expect(task_details[:run_level]).to eq("HighestAvailable")
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ context "when start_day and start_time is set" do
+ it "creates task to activate on '09/10/2018' at '15:00' when start_day = '09/10/2018' and start_time = '15:00' provided" do
+ subject.start_day "09/10/2018"
+ subject.start_time "15:00"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(9)
+ expect(trigger_details[:start_year]).to eq("2018")
+ expect(trigger_details[:start_month]).to eq("09")
+ expect(trigger_details[:start_day]).to eq("10")
+ expect(trigger_details[:start_hour]).to eq("15")
+ expect(trigger_details[:start_minute]).to eq("00")
+ end
end
end
@@ -232,25 +982,56 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource.command task_name
new_resource.run_level :highest
new_resource.frequency :on_idle
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
context "when idle_time is not passed" do
it "raises error" do
- expect { subject.run_action(:create) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
+ expect { subject.after_created }.to raise_error("idle_time value should be set for :on_idle frequency.")
end
end
context "when idle_time is passed" do
it "creates the scheduled task to run when system is idle" do
subject.idle_time 20
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(6)
+ expect(current_resource.task.settings[:idle_settings][:idle_duration]).to eq("PT20M")
+ expect(current_resource.task.settings[:run_only_if_idle]).to eq(true)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.idle_time 20
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:ScheduleType]).to eq("At idle time")
- expect(task_details[:run_level]).to eq("HighestAvailable")
- expect(task_details[:idle_time]).to eq("PT20M")
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "when start_day and start_time is set" do
+ it "creates task to activate on '09/10/2018' at '15:00' when start_day = '09/10/2018' and start_time = '15:00' provided" do
+ subject.idle_time 20
+ subject.start_day "09/10/2018"
+ subject.start_time "15:00"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(trigger_details[:trigger_type]).to eq(6)
+ expect(trigger_details[:start_year]).to eq("2018")
+ expect(trigger_details[:start_month]).to eq("09")
+ expect(trigger_details[:start_day]).to eq("10")
+ expect(trigger_details[:start_hour]).to eq("15")
+ expect(trigger_details[:start_minute]).to eq("00")
end
end
end
@@ -260,31 +1041,309 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
new_resource.run_level :highest
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
it "sets the random_delay for frequency :minute" do
subject.frequency :minute
- subject.random_delay "PT20M"
+ subject.random_delay "20"
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ trigger_details = current_resource.task.trigger(0)
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(trigger_details[:trigger_type]).to eq(1)
+ expect(trigger_details[:random_minutes_interval]).to eq(20)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.frequency :minute
+ subject.random_delay "20"
+ subject.run_action(:create)
subject.run_action(:create)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:TaskName]).to eq("\\chef-client")
- expect(task_details[:ScheduleType]).to eq("One Time Only, Minute")
- expect(task_details[:TaskToRun]).to eq("chef-client")
- expect(task_details[:run_level]).to eq("HighestAvailable")
- expect(task_details[:random_delay]).to eq("PT20M")
+ expect(subject).not_to be_updated_by_last_action
end
it "raises error if invalid random_delay is passed" do
subject.frequency :minute
subject.random_delay "abc"
- expect { subject.after_created }.to raise_error("Invalid value passed for `random_delay`. Please pass seconds as a String e.g. '60'.")
+ expect { subject.after_created }.to raise_error("Invalid value passed for `random_delay`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60').")
end
it "raises error if random_delay is passed with frequency on_idle" do
subject.frequency :on_idle
- subject.random_delay "PT20M"
- expect { subject.after_created }.to raise_error("`random_delay` property is supported only for frequency :minute, :hourly, :daily, :weekly and :monthly")
+ subject.random_delay "20"
+ expect { subject.after_created }.to raise_error("`random_delay` property is supported only for frequency :once, :minute, :hourly, :daily, :weekly and :monthly")
+ end
+ end
+
+ context "frequency :none" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :none
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates the scheduled task to run on demand only" do
+ call_for_create_action
+ # loading current resource again to check new task is creted and it matches task parameters
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+
+ expect(current_resource.task.application_name).to eq(task_name)
+ expect(current_resource.task.principals[:run_level]).to eq(1)
+ expect(current_resource.task.trigger_count).to eq(0)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+ end
+
+ context "task_name with parent folder" do
+ describe "task_name with path '\\foo\\chef-client-functional-test' " do
+ let(:task_name) { "\\foo\\chef-client-functional-test" }
+ after { delete_task }
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :once
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates the scheduled task with task name 'chef-client-functional-test' inside path '\\foo'" do
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq(task_name)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ describe "task_name with path '\\foo\\bar\\chef-client-functional-test' " do
+ let(:task_name) { "\\foo\\bar\\chef-client-functional-test" }
+ after { delete_task }
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :once
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "creates the scheduled task with task with name 'chef-client-functional-test' inside path '\\foo\\bar' " do
+ call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(true)
+ expect(current_resource.task.application_name).to eq(task_name)
+ end
+
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+ end
+
+ describe "Examples of idempotent checks for each frequency" do
+ after { delete_task }
+ context "For frequency :once" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :once
+ new_resource.start_time "17:00"
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier as 1" do
+ subject.frequency_modifier 1
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "create task by adding frequency_modifier as 5" do
+ subject.frequency_modifier 5
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :none" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource.frequency :none
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier as 1" do
+ subject.frequency_modifier 1
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "create task by adding frequency_modifier as 5" do
+ subject.frequency_modifier 5
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :weekly" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :weekly
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding start_day" do
+ subject.start_day "12/28/2018"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "create task by adding frequency_modifier and random_delay" do
+ subject.frequency_modifier 3
+ subject.random_delay "60"
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :monthly" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :once
+ new_resource.start_time "17:00"
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier as 1" do
+ subject.frequency_modifier 1
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "create task by adding frequency_modifier as 5" do
+ subject.frequency_modifier 5
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :hourly" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :hourly
+ new_resource.frequency_modifier 5
+ new_resource.random_delay "2400"
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier and random_delay" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :daily" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :daily
+ new_resource.frequency_modifier 2
+ new_resource.random_delay "2400"
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier and random_delay" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :on_logon" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.frequency :on_logon
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier and random_delay" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "create task by adding frequency_modifier as 5" do
+ subject.frequency_modifier 5
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
+ end
+ end
+
+ context "For frequency :onstart" do
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.run_level :highest
+ new_resource.frequency :onstart
+ new_resource.frequency_modifier 20
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource
+ end
+
+ it "create task by adding frequency_modifier as 20" do
+ subject.run_action(:create)
+ subject.run_action(:create)
+ expect(subject).not_to be_updated_by_last_action
end
end
end
@@ -294,14 +1353,15 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
new_resource.run_level :highest
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
new_resource
end
context "when start_day is passed with frequency :onstart" do
- it "raises error" do
+ it "not raises error" do
subject.frequency :onstart
- subject.start_day "mon"
- expect { subject.after_created }.to raise_error("`start_day` property is not supported with frequency: onstart")
+ subject.start_day "09/20/2017"
+ expect { subject.after_created }.not_to raise_error
end
end
@@ -309,7 +1369,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
it "raises error" do
subject.user "Administrator"
subject.frequency :onstart
- expect { subject.after_created }.to raise_error("Can't specify a non-system user without a password!")
+ expect { subject.after_created }.to raise_error(%q{Cannot specify a user other than the system users without specifying a password!. Valid passwordless users: 'NT AUTHORITY\SYSTEM', 'SYSTEM', 'NT AUTHORITY\LOCALSERVICE', 'NT AUTHORITY\NETWORKSERVICE', 'BUILTIN\USERS', 'USERS'})
end
end
@@ -325,7 +1385,47 @@ describe Chef::Resource::WindowsTask, :windows_only do
it "raises error" do
subject.frequency_modifier 1450
subject.frequency :minute
- expect { subject.after_created }.to raise_error("frequency_modifier value 1450 is invalid. Valid values for :minute frequency are 1 - 1439.")
+ expect { subject.after_created }.to raise_error("frequency_modifier value 1450 is invalid. Valid values for :minute frequency are 1 - 1439.")
+ end
+ end
+
+ context "when frequency_modifier > 23 is passed for frequency=:minute" do
+ it "raises error" do
+ subject.frequency_modifier 24
+ subject.frequency :hourly
+ expect { subject.after_created }.to raise_error("frequency_modifier value 24 is invalid. Valid values for :hourly frequency are 1 - 23.")
+ end
+ end
+
+ context "when frequency_modifier > 23 is passed for frequency=:minute" do
+ it "raises error" do
+ subject.frequency_modifier 366
+ subject.frequency :daily
+ expect { subject.after_created }.to raise_error("frequency_modifier value 366 is invalid. Valid values for :daily frequency are 1 - 365.")
+ end
+ end
+
+ context "when frequency_modifier > 52 is passed for frequency=:minute" do
+ it "raises error" do
+ subject.frequency_modifier 53
+ subject.frequency :weekly
+ expect { subject.after_created }.to raise_error("frequency_modifier value 53 is invalid. Valid values for :weekly frequency are 1 - 52.")
+ end
+ end
+
+ context "when invalid frequency_modifier is passed for :monthly frequency" do
+ it "raises error" do
+ subject.frequency :monthly
+ subject.frequency_modifier "13"
+ expect { subject.after_created }.to raise_error("frequency_modifier value 13 is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
+ end
+ end
+
+ context "when invalid frequency_modifier is passed for :monthly frequency" do
+ it "raises error" do
+ subject.frequency :monthly
+ subject.frequency_modifier "xyz"
+ expect { subject.after_created }.to raise_error("frequency_modifier value xyz is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
end
end
@@ -333,7 +1433,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
it "raises error" do
subject.months "xyz"
subject.frequency :monthly
- expect { subject.after_created }.to raise_error("months attribute invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC and *. Multiple values must be separated by a comma.")
+ expect { subject.after_created }.to raise_error("months property invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC, *. Multiple values must be separated by a comma.")
end
end
@@ -341,7 +1441,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
it "raises error" do
subject.idle_time 1000
subject.frequency :on_idle
- expect { subject.after_created }.to raise_error("idle_time value 1000 is invalid. Valid values for :on_idle frequency are 1 - 999.")
+ expect { subject.after_created }.to raise_error("idle_time value 1000 is invalid. Valid values for :on_idle frequency are 1 - 999.")
end
end
@@ -349,7 +1449,7 @@ describe Chef::Resource::WindowsTask, :windows_only do
it "raises error" do
subject.idle_time 300
subject.frequency :monthly
- expect { subject.after_created }.to raise_error("idle_time attribute is only valid for tasks that run on_idle")
+ expect { subject.after_created }.to raise_error("idle_time property is only valid for tasks that run on_idle")
end
end
end
@@ -358,14 +1458,23 @@ describe Chef::Resource::WindowsTask, :windows_only do
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since win32-taskscheduler accespts this
+ new_resource.frequency :hourly
new_resource
end
- it "deletes the task if it exists" do
+ it "does not converge the resource if it is already converged" do
+ subject.run_action(:create)
+ subject.run_action(:delete)
+ subject.run_action(:delete)
+ expect(subject).not_to be_updated_by_last_action
+ end
+
+ it "does not converge the resource if it is already converged" do
subject.run_action(:create)
- delete_task
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details).to eq(false)
+ subject.run_action(:delete)
+ subject.run_action(:delete)
+ expect(subject).not_to be_updated_by_last_action
end
end
@@ -376,15 +1485,16 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command "dir"
new_resource.run_level :highest
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since
+ new_resource.frequency :hourly
new_resource
end
it "runs the existing task" do
- skip "Task status is returned as Ready instead of Running randomly"
subject.run_action(:create)
subject.run_action(:run)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:Status]).to eq("Running")
+ current_resource = call_for_load_current_resource
+ expect(current_resource.task.status).to eq("queued").or eq("running").or eq("ready") # queued or can be running
end
end
@@ -395,53 +1505,75 @@ describe Chef::Resource::WindowsTask, :windows_only do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command "dir"
new_resource.run_level :highest
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since
new_resource
end
it "ends the running task" do
subject.run_action(:create)
subject.run_action(:run)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
subject.run_action(:end)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:Status]).to eq("Ready")
+ current_resource = call_for_load_current_resource
+ expect(current_resource.task.status).to eq("queued").or eq("ready") # queued or can be ready
end
end
describe "action :enable" do
+ let(:task_name) { "chef-client-functional-test-enable" }
after { delete_task }
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since
+ new_resource.frequency :hourly
new_resource
end
it "enables the disabled task" do
subject.run_action(:create)
subject.run_action(:disable)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:ScheduledTaskState]).to eq("Disabled")
+ current_resource = call_for_load_current_resource
+ expect(current_resource.task.status).to eq("not scheduled")
subject.run_action(:enable)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:ScheduledTaskState]).to eq("Enabled")
+ current_resource = call_for_load_current_resource
+ expect(current_resource.task.status).to eq("ready")
end
end
describe "action :disable" do
+ let(:task_name) { "chef-client-functional-test-disable" }
after { delete_task }
subject do
new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
new_resource.command task_name
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since
+ new_resource.frequency :hourly
new_resource
end
it "disables the task" do
subject.run_action(:create)
subject.run_action(:disable)
- task_details = windows_task_provider.send(:load_task_hash, task_name)
- expect(task_details[:ScheduledTaskState]).to eq("Disabled")
+ current_resource = call_for_load_current_resource
+ expect(current_resource.task.status).to eq("not scheduled")
+ end
+ end
+
+ describe "action :change" do
+ after { delete_task }
+ subject do
+ new_resource = Chef::Resource::WindowsTask.new(task_name, run_context)
+ new_resource.command task_name
+ new_resource.execution_time_limit = 259200 / 60 # converting "PT72H" into minutes and passing here since
+ new_resource.frequency :hourly
+ new_resource
+ end
+
+ it "call action_create since change action is alias for create" do
+ subject.run_action(:change)
+ expect(subject).to be_updated_by_last_action
end
end
@@ -449,4 +1581,15 @@ describe Chef::Resource::WindowsTask, :windows_only do
task_to_delete = Chef::Resource::WindowsTask.new(task_name, run_context)
task_to_delete.run_action(:delete)
end
+
+ def call_for_create_action
+ current_resource = call_for_load_current_resource
+ expect(current_resource.exists).to eq(false)
+ subject.run_action(:create)
+ expect(subject).to be_updated_by_last_action
+ end
+
+ def call_for_load_current_resource
+ windows_task_provider.send(:load_current_resource)
+ end
end
diff --git a/spec/functional/resource/yum_package_spec.rb b/spec/functional/resource/yum_package_spec.rb
new file mode 100644
index 0000000000..5075c24ea0
--- /dev/null
+++ b/spec/functional/resource/yum_package_spec.rb
@@ -0,0 +1,957 @@
+#
+# Copyright:: Copyright 2016-2018, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "functional/resource/base"
+require "chef/mixin/shell_out"
+
+# run this test only for following platforms.
+exclude_test = !(%w{rhel fedora}.include?(ohai[:platform_family]) && !File.exist?("/usr/bin/dnf"))
+describe Chef::Resource::YumPackage, :requires_root, external: exclude_test do
+ include Chef::Mixin::ShellOut
+
+ # NOTE: every single test here either needs to explicitly call flush_cache or needs to explicitly
+ # call preinstall (which explicitly calls flush_cache). It is your responsibility to do one or the
+ # other in order to minimize calling flush_cache a half dozen times per test.
+
+ def flush_cache
+ Chef::Resource::YumPackage.new("shouldnt-matter", run_context).run_action(:flush_cache)
+ end
+
+ def preinstall(*rpms)
+ rpms.each do |rpm|
+ shell_out!("rpm -ivh #{CHEF_SPEC_ASSETS}/yumrepo/#{rpm}")
+ end
+ flush_cache
+ end
+
+ before(:all) do
+ shell_out!("yum -y install yum-utils")
+ end
+
+ before(:each) do
+ File.open("/etc/yum.repos.d/chef-yum-localtesting.repo", "w+") do |f|
+ f.write <<~EOF
+ [chef-yum-localtesting]
+ name=Chef DNF spec testing repo
+ baseurl=file://#{CHEF_SPEC_ASSETS}/yumrepo
+ enable=1
+ gpgcheck=0
+ EOF
+ end
+ shell_out!("rpm -qa --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' | grep chef_rpm | xargs -r rpm -e")
+ # next line is useful cleanup if you happen to have been testing both yum + dnf func tests on the same box and
+ # have some dnf garbage left around
+ FileUtils.rm_f "/etc/yum.repos.d/chef-dnf-localtesting.repo"
+ end
+
+ after(:all) do
+ shell_out!("rpm -qa --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' | grep chef_rpm | xargs -r rpm -e")
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ end
+
+ let(:package_name) { "chef_rpm" }
+ let(:yum_package) do
+ r = Chef::Resource::YumPackage.new(package_name, run_context)
+ r.options("--nogpgcheck")
+ r
+ end
+
+ def pkg_arch
+ ohai[:kernel][:machine]
+ end
+
+ describe ":install" do
+ context "vanilla use case" do
+ let(:package_name) { "chef_rpm" }
+
+ it "installs if the package is not installed" do
+ flush_cache
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "does not install if the package is installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "does not install twice" do
+ flush_cache
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "does not install if the prior version package is installed" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "does not install if the i686 package is installed", :intel_64bit do
+ skip "FIXME: do nothing, or install the #{pkg_arch} version?"
+ preinstall("chef_rpm-1.10-1.i686.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.i686$")
+ end
+
+ it "does not install if the prior version i686 package is installed", :intel_64bit do
+ skip "FIXME: do nothing, or install the #{pkg_arch} version?"
+ preinstall("chef_rpm-1.2-1.i686.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.i686$")
+ end
+ end
+
+ context "with versions or globs in the name" do
+ it "works with a version" do
+ flush_cache
+ yum_package.package_name("chef_rpm-1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "works with an older version" do
+ flush_cache
+ yum_package.package_name("chef_rpm-1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "works with an evra" do
+ flush_cache
+ yum_package.package_name("chef_rpm-0:1.2-1.#{pkg_arch}")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "works with version and release" do
+ flush_cache
+ yum_package.package_name("chef_rpm-1.2-1")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "works with a version glob" do
+ flush_cache
+ yum_package.package_name("chef_rpm-1*")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "works with a name glob + version glob" do
+ flush_cache
+ yum_package.package_name("chef_rp*-1*")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "upgrades when the installed version does not match the version string" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm-1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}")
+ end
+
+ it "downgrades when the installed version is higher than the package_name version" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm-1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ # version only matches the actual yum version, does not work with epoch or release or combined evr
+ context "with version property" do
+ it "matches the full version" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "matches with a glob" do
+ # we are unlikely to ever fix this. if you've found this comment you should use e.g. "tcpdump-4*" in
+ # the name field rather than trying to use a name of "tcpdump" and a version of "4*".
+ pending "this does not work, is not easily supported by the underlying yum libraries, but does work in the new dnf_package provider"
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("1*")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "matches the vr" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("1.10-1")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "matches the evr" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("0:1.10-1")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "matches with a vr glob" do
+ pending "doesn't work on command line either"
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("1.10-1*")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "matches with an evr glob" do
+ pending "doesn't work on command line either"
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.version("0:1.10-1*")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+ end
+
+ context "downgrades" do
+ it "downgrades the package when allow_downgrade" do
+ flush_cache
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm")
+ yum_package.allow_downgrade true
+ yum_package.version("1.2-1")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "with arches", :intel_64bit do
+ it "installs with 64-bit arch in the name" do
+ flush_cache
+ yum_package.package_name("chef_rpm.#{pkg_arch}")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "installs with 32-bit arch in the name" do
+ flush_cache
+ yum_package.package_name("chef_rpm.i686")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.i686$")
+ end
+
+ it "installs with 64-bit arch in the property" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.arch((pkg_arch).to_s)
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "installs with 32-bit arch in the property" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.arch("i686")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.i686$")
+ end
+ end
+
+ context "with constraints" do
+ it "with nothing installed, it installs the latest version", not_rhel5: true do
+ flush_cache
+ yum_package.package_name("chef_rpm >= 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "when it is met, it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm >= 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "when it is met, it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm >= 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with nothing intalled, it installs the latest version", not_rhel5: true do
+ flush_cache
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "when it is not met by an installed rpm, it upgrades", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with an equality constraint, when it is not met by an installed rpm, it upgrades", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm = 1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with an equality constraint, when it is met by an installed rpm, it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm = 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "when it is met by an installed rpm, it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "when there is no solution to the contraint", not_rhel5: true do
+ flush_cache
+ yum_package.package_name("chef_rpm > 2.0")
+ expect { yum_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
+ end
+
+ it "when there is no solution to the contraint but an rpm is preinstalled", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm > 2.0")
+ expect { yum_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
+ end
+
+ it "with a less than constraint, when nothing is installed, it installs", not_rhel5: true do
+ flush_cache
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a less than constraint, when the install version matches, it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a less than constraint, when the install version fails, it should downgrade", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "with source arguments" do
+ it "raises an exception when the package does not exist" do
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/this-file-better-not-exist.rpm")
+ expect { yum_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
+ end
+
+ it "does not raise a hard exception in why-run mode when the package does not exist" do
+ Chef::Config[:why_run] = true
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/this-file-better-not-exist.rpm")
+ yum_package.run_action(:install)
+ expect { yum_package.run_action(:install) }.not_to raise_error
+ end
+
+ it "installs the package when using the source argument" do
+ flush_cache
+ yum_package.name "something"
+ yum_package.package_name "somethingelse"
+ yum_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "installs the package when the name is a path to a file" do
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "downgrade on a local file raises an error", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.version "1.2-1"
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ expect { yum_package.run_action(:install) }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
+ end
+
+ it "downgrade on a local file with allow_downgrade true works" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.version "1.2-1"
+ yum_package.allow_downgrade true
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "does not downgrade the package with :install" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "does not upgrade the package with :install" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "is idempotent when the package is already installed" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "with no available version" do
+ it "works when a package is installed" do
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "works with a local source" do
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "multipackage with arches", :intel_64bit do
+ it "installs two rpms" do
+ flush_cache
+ yum_package.package_name([ "chef_rpm.#{pkg_arch}", "chef_rpm.i686" ] )
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ it "does nothing if both are installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm", "chef_rpm-1.10-1.i686.rpm")
+ flush_cache
+ yum_package.package_name([ "chef_rpm.#{pkg_arch}", "chef_rpm.i686" ] )
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ end
+
+ it "installs the second rpm if the first is installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name([ "chef_rpm.#{pkg_arch}", "chef_rpm.i686" ] )
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ it "installs the first rpm if the second is installed" do
+ preinstall("chef_rpm-1.10-1.i686.rpm")
+ yum_package.package_name([ "chef_rpm.#{pkg_arch}", "chef_rpm.i686" ] )
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ # unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
+ it "installs two rpms with multi-arch" do
+ flush_cache
+ yum_package.package_name(%w{chef_rpm chef_rpm} )
+ yum_package.arch([pkg_arch, "i686"])
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ # unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
+ it "installs the second rpm if the first is installed (muti-arch)" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name(%w{chef_rpm chef_rpm} )
+ yum_package.arch([pkg_arch, "i686"])
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ # unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
+ it "installs the first rpm if the second is installed (muti-arch)" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name(%w{chef_rpm chef_rpm} )
+ yum_package.arch([pkg_arch, "i686"])
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.#{pkg_arch}$/)
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match(/^chef_rpm-1.10-1.i686$/)
+ end
+
+ # unlikely to work consistently correct, okay to deprecate the arch-array in favor of the arch in the name
+ it "does nothing if both are installed (muti-arch)" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm", "chef_rpm-1.10-1.i686.rpm")
+ yum_package.package_name(%w{chef_rpm chef_rpm} )
+ yum_package.arch([pkg_arch, "i686"])
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be false
+ end
+ end
+
+ context "repo controls" do
+ it "should fail with the repo disabled" do
+ flush_cache
+ yum_package.options("--disablerepo=chef-yum-localtesting")
+ expect { yum_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
+ end
+
+ it "should work with disablerepo first" do
+ flush_cache
+ yum_package.options(["--disablerepo=*", "--enablerepo=chef-yum-localtesting"])
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "should work to enable a disabled repo", not_rhel5: true do
+ shell_out!("yum-config-manager --disable chef-yum-localtesting")
+ flush_cache
+ expect { yum_package.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /No candidate version available/)
+ flush_cache
+ yum_package.options("--enablerepo=chef-yum-localtesting")
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "when an idempotent install action is run, does not leave repos disabled" do
+ flush_cache
+ # this is a bit tricky -- we need this action to be idempotent, so that it doesn't recycle any
+ # caches, but need it to hit whatavailable with the repo disabled. using :upgrade like this
+ # accomplishes both those goals (it would be easier if we had other rpms in this repo, but with
+ # one rpm we neeed to do this).
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.options("--disablerepo=chef-yum-localtesting")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ # now we're still using the same cache in the yum_helper.py cache and we test to see if the
+ # repo that we temporarily disabled is enabled on this pass.
+ yum_package.package_name("chef_rpm-1.10-1.#{pkg_arch}")
+ yum_package.options(nil)
+ yum_package.run_action(:install)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+ end
+ end
+
+ describe ":upgrade" do
+
+ context "with source arguments" do
+ it "installs the package when using the source argument" do
+ flush_cache
+ yum_package.name "something"
+ yum_package.package_name "somethingelse"
+ yum_package.source("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "installs the package when the name is a path to a file" do
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "downgrades the package when allow_downgrade is true" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "upgrades the package" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "is idempotent when the package is already installed" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "with no available version" do
+ it "works when a package is installed" do
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "works with a local source" do
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ flush_cache
+ yum_package.package_name("#{CHEF_SPEC_ASSETS}/yumrepo/chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+
+ context "version pinning" do
+ it "with an equality pin in the name it upgrades a prior package" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm-1.10")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with a prco equality pin in the name it upgrades a prior package", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm == 1.10")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with an equality pin in the name it downgrades a later package" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm-1.2")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a prco equality pin in the name it downgrades a later package", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm == 1.2")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a > pin in the name and no rpm installed it installs", not_rhel5: true do
+ flush_cache
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with a < pin in the name and no rpm installed it installs", not_rhel5: true do
+ flush_cache
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a > pin in the name and matching rpm installed it does nothing", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with a < pin in the name and no rpm installed it installs", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+
+ it "with a > pin in the name and non-matching rpm installed it upgrades", not_rhel5: true do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.package_name("chef_rpm > 1.2")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+
+ it "with a < pin in the name and non-matching rpm installed it downgrades", not_rhel5: true do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.allow_downgrade true
+ yum_package.package_name("chef_rpm < 1.10")
+ yum_package.run_action(:upgrade)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.#{pkg_arch}$")
+ end
+ end
+ end
+
+ describe ":remove" do
+ context "vanilla use case" do
+ let(:package_name) { "chef_rpm" }
+ it "does nothing if the package is not installed" do
+ flush_cache
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the package is installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "does not remove the package twice" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the prior version package is installed" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the i686 package is installed", :intel_64bit do
+ skip "FIXME: should this be fixed or is the current behavior correct?"
+ preinstall("chef_rpm-1.10-1.i686.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the prior version i686 package is installed", :intel_64bit do
+ skip "FIXME: should this be fixed or is the current behavior correct?"
+ preinstall("chef_rpm-1.2-1.i686.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+ end
+
+ context "with 64-bit arch", :intel_64bit do
+ let(:package_name) { "chef_rpm.#{pkg_arch}" }
+ it "does nothing if the package is not installed" do
+ flush_cache
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the package is installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "removes the package if the prior version package is installed" do
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+
+ it "does nothing if the i686 package is installed" do
+ preinstall("chef_rpm-1.10-1.i686.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.i686$")
+ end
+
+ it "does nothing if the prior version i686 package is installed" do
+ preinstall("chef_rpm-1.2-1.i686.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.2-1.i686$")
+ end
+ end
+
+ context "with 32-bit arch", :intel_64bit do
+ let(:package_name) { "chef_rpm.i686" }
+ it "removes only the 32-bit arch if both are installed" do
+ preinstall("chef_rpm-1.10-1.#{pkg_arch}.rpm", "chef_rpm-1.10-1.i686.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^chef_rpm-1.10-1.#{pkg_arch}$")
+ end
+ end
+
+ context "with no available version" do
+ it "works when a package is installed" do
+ FileUtils.rm_f "/etc/yum.repos.d/chef-yum-localtesting.repo"
+ preinstall("chef_rpm-1.2-1.#{pkg_arch}.rpm")
+ yum_package.run_action(:remove)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("rpm -q --queryformat '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n' chef_rpm").stdout.chomp).to match("^package chef_rpm is not installed$")
+ end
+ end
+ end
+
+ describe ":lock and :unlock" do
+ before(:all) do
+ shell_out!("yum -y install yum-versionlock")
+ end
+
+ before(:each) do
+ shell_out("yum versionlock delete '*:chef_rpm-*'") # will exit with error when nothing is locked, we don't care
+ end
+
+ it "locks an rpm" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.run_action(:lock)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("yum versionlock list").stdout.chomp).to match("^0:chef_rpm-")
+ end
+
+ it "does not lock if its already locked" do
+ flush_cache
+ shell_out!("yum versionlock add chef_rpm")
+ yum_package.package_name("chef_rpm")
+ yum_package.run_action(:lock)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("yum versionlock list").stdout.chomp).to match("^0:chef_rpm-")
+ end
+
+ it "unlocks an rpm" do
+ flush_cache
+ shell_out!("yum versionlock add chef_rpm")
+ yum_package.package_name("chef_rpm")
+ yum_package.run_action(:unlock)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("yum versionlock list").stdout.chomp).not_to match("^0:chef_rpm-")
+ end
+
+ it "does not unlock an already locked rpm" do
+ flush_cache
+ yum_package.package_name("chef_rpm")
+ yum_package.run_action(:unlock)
+ expect(yum_package.updated_by_last_action?).to be false
+ expect(shell_out("yum versionlock list").stdout.chomp).not_to match("^0:chef_rpm-")
+ end
+
+ it "check that we can lock based on provides" do
+ flush_cache
+ yum_package.package_name("chef_rpm_provides")
+ yum_package.run_action(:lock)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("yum versionlock list").stdout.chomp).to match("^0:chef_rpm-")
+ end
+
+ it "check that we can unlock based on provides" do
+ flush_cache
+ shell_out!("yum versionlock add chef_rpm")
+ yum_package.package_name("chef_rpm_provides")
+ yum_package.run_action(:unlock)
+ expect(yum_package.updated_by_last_action?).to be true
+ expect(shell_out("yum versionlock list").stdout.chomp).not_to match("^0:chef_rpm-")
+ end
+ end
+end
diff --git a/spec/functional/root_alias_spec.rb b/spec/functional/root_alias_spec.rb
index 7091615d12..a0a63011b4 100644
--- a/spec/functional/root_alias_spec.rb
+++ b/spec/functional/root_alias_spec.rb
@@ -49,7 +49,7 @@ describe "root aliases" do
context "with both an attributes.rb and attributes/default.rb" do
it "should log an error and ignore attributes/default.rb" do
- expect(Chef::Log).to receive(:error).with("Cookbook dup_attr contains both attributes.rb and and attributes/default.rb, ignoring attributes/default.rb")
+ expect_any_instance_of(Mixlib::Log::Child).to receive(:error).with("Cookbook dup_attr contains both attributes.rb and and attributes/default.rb, ignoring attributes/default.rb")
node.run_list << "dup_attr"
run_context.load(node.run_list.expand("_default"))
expect(node["aliased"]["attr"]).to eq "value"
diff --git a/spec/functional/run_lock_spec.rb b/spec/functional/run_lock_spec.rb
index d270803698..49972360ef 100644
--- a/spec/functional/run_lock_spec.rb
+++ b/spec/functional/run_lock_spec.rb
@@ -21,7 +21,7 @@ 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
+ describe "when locking the chef-client run", unix_only: true do
##
# Lockfile location and helpers
@@ -150,7 +150,7 @@ describe Chef::RunLock do
end
end
- it "sets FD_CLOEXEC on the lockfile", :supports_cloexec => true do
+ it "sets FD_CLOEXEC on the lockfile", supports_cloexec: true do
run_lock = File.open(lockfile)
expect(run_lock.fcntl(Fcntl::F_GETFD, 0) & Fcntl::FD_CLOEXEC).to eq(Fcntl::FD_CLOEXEC)
end
@@ -197,7 +197,7 @@ describe Chef::RunLock do
end
end
- it "sets FD_CLOEXEC on the lockfile", :supports_cloexec => true do
+ it "sets FD_CLOEXEC on the lockfile", supports_cloexec: true do
run_lock = File.open(lockfile)
expect(run_lock.fcntl(Fcntl::F_GETFD, 0) & Fcntl::FD_CLOEXEC).to eq(Fcntl::FD_CLOEXEC)
end
@@ -461,7 +461,7 @@ describe Chef::RunLock do
buffer << fd.read_nonblock(1) while buffer[-1] != "\n"
buffer
- #rescue IO::EAGAINUnreadable
+ # rescue IO::EAGAINUnreadable
rescue IO::WaitReadable
unless buffer == ""
sleep 0.1
diff --git a/spec/functional/shell_spec.rb b/spec/functional/shell_spec.rb
index 08c791f2d2..3990f1afe0 100644
--- a/spec/functional/shell_spec.rb
+++ b/spec/functional/shell_spec.rb
@@ -26,7 +26,7 @@ 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
+ describe "smoke tests", unix_only: true do
TIMEOUT = 300
diff --git a/spec/functional/util/powershell/cmdlet_spec.rb b/spec/functional/util/powershell/cmdlet_spec.rb
index 19f5e58a49..4be021a60b 100644
--- a/spec/functional/util/powershell/cmdlet_spec.rb
+++ b/spec/functional/util/powershell/cmdlet_spec.rb
@@ -25,10 +25,10 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do
@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") }
@@ -58,7 +58,7 @@ 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
@@ -68,7 +68,7 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do
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!
@@ -95,7 +95,7 @@ describe Chef::Util::Powershell::Cmdlet, :windows_powershell_dsc_only do
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")
diff --git a/spec/functional/version_spec.rb b/spec/functional/version_spec.rb
index a45c25ff8c..dc323e9d3a 100644
--- a/spec/functional/version_spec.rb
+++ b/spec/functional/version_spec.rb
@@ -28,7 +28,7 @@ describe "Chef Versions" do
binaries.each do |binary|
it "#{binary} version should be sane" do
- expect(shell_out!("ruby #{File.join("bin", binary)} -v", :cwd => chef_dir).stdout.chomp).to include("Chef: #{Chef::VERSION}")
+ expect(shell_out!("ruby #{File.join("bin", binary)} -v", cwd: chef_dir).stdout.chomp).to include("Chef: #{Chef::VERSION}")
end
end
diff --git a/spec/functional/win32/crypto_spec.rb b/spec/functional/win32/crypto_spec.rb
index 145c9881b9..5fcbca02b6 100644
--- a/spec/functional/win32/crypto_spec.rb
+++ b/spec/functional/win32/crypto_spec.rb
@@ -37,15 +37,15 @@ describe "Chef::ReservedNames::Win32::Crypto", :windows_only do
it "can be decrypted by powershell" do
encrypted = Chef::ReservedNames::Win32::Crypto.encrypt(plaintext)
resource = Chef::Resource::WindowsScript::PowershellScript.new("Powershell resource functional test", @run_context)
- resource.code <<-EOF
-$encrypted = '#{encrypted}' | ConvertTo-SecureString
-$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($encrypted)
-$plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
-if ($plaintext -ne '#{plaintext}') {
- Write-Error 'Got: ' $plaintext
- exit 1
-}
-exit 0
+ resource.code <<~EOF
+ $encrypted = '#{encrypted}' | ConvertTo-SecureString
+ $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($encrypted)
+ $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
+ if ($plaintext -ne '#{plaintext}') {
+ Write-Error 'Got: ' $plaintext
+ exit 1
+ }
+ exit 0
EOF
resource.returns(0)
resource.run_action(:run)
diff --git a/spec/functional/win32/registry_spec.rb b/spec/functional/win32/registry_spec.rb
index bcfa0ffd48..923b952161 100644
--- a/spec/functional/win32/registry_spec.rb
+++ b/spec/functional/win32/registry_spec.rb
@@ -23,7 +23,7 @@ require "chef/win32/registry"
describe "Chef::Win32::Registry", :windows_only do
before(:all) do
- #Create a registry item
+ # Create a registry item
::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root"
::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root\\Branch"
::Win32::Registry::HKEY_CURRENT_USER.create "Software\\Root\\B®anch"
@@ -39,17 +39,17 @@ describe "Chef::Win32::Registry", :windows_only do
reg["Petals", Win32::Registry::REG_MULTI_SZ] = %w{Pink Delicate}
end
- #Create the node with ohai data
+ # Create the node with ohai data
events = Chef::EventDispatch::Dispatcher.new
@node = Chef::Node.new
@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
+ # Create a registry object that has access ot the node previously created
@registry = Chef::Win32::Registry.new(@run_context)
end
- #Delete what is left of the registry key-values previously created
+ # Delete what is left of the registry key-values previously created
after(:all) do
::Win32::Registry::HKEY_CURRENT_USER.open("Software") do |reg|
reg.delete_key("Root", true)
@@ -102,85 +102,85 @@ describe "Chef::Win32::Registry", :windows_only do
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 => %w{Pink Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing)
+ expect { @registry.data_exists?("JKLM\\Software\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing)
+ expect { @registry.data_exists?("HKCU\\Software\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} })).to eq(true)
+ expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} })).to eq(true)
+ expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { name: "petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} })).to eq(false)
+ expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { name: "slateP", type: :multi_string, data: %w{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 => %w{Mauve Delicate} })).to eq(false)
+ expect(@registry.data_exists?("HKCU\\Software\\Root\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegHiveMissing)
+ expect { @registry.data_exists!("JKLM\\Software\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing)
+ expect { @registry.data_exists!("HKCU\\Software\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} })).to eq(true)
+ expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} })).to eq(true)
+ expect(@registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { name: "petals", type: :multi_string, data: %w{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 => %w{Pink Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing)
+ expect { @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { name: "slateP", type: :multi_string, data: %w{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 => %w{Mauve Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing)
+ expect { @registry.data_exists!("HKCU\\Software\\Root\\Branch\\Flower", { name: "Petals", type: :multi_string, data: %w{Mauve Delicate} }) }.to raise_error(Chef::Exceptions::Win32RegDataMissing)
end
end
@@ -188,8 +188,8 @@ 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
@@ -203,70 +203,70 @@ describe "Chef::Win32::Registry", :windows_only do
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 => %w{one two} }) }.to raise_error NoMethodError
+ expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { name: "ShouldThrow", type: :dword, data: %w{one two} }) }.to raise_error NoMethodError
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 => %w{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: %w{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 NoMethodError
+ expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { name: "ShouldThrow", type: :multi_string, data: 65535 }) }.to raise_error NoMethodError
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 NoMethodError
+ expect { @registry.set_value("HKCU\\Software\\Root\\Branch\\Flower", { name: "ShouldBeWat", type: :multi_string, data: "foo" }) }.to raise_error NoMethodError
end
end
@@ -309,21 +309,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
@@ -566,38 +566,38 @@ describe "Chef::Win32::Registry", :windows_only do
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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ 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)
+ expect { @registry.data_exists?("HKLM\\Software\\Root\\Poosh", { name: "Status", type: :string, data: "Lost" }) }.to raise_error(Chef::Exceptions::Win32RegKeyMissing)
end
end
diff --git a/spec/functional/win32/security_spec.rb b/spec/functional/win32/security_spec.rb
index 40ae99bfa4..5ef1f250ea 100644
--- a/spec/functional/win32/security_spec.rb
+++ b/spec/functional/win32/security_spec.rb
@@ -17,6 +17,8 @@
#
require "spec_helper"
+require "mixlib/shellout"
+require "chef/mixin/user_context"
if Chef::Platform.windows?
require "chef/win32/security"
end
@@ -26,13 +28,37 @@ describe "Chef::Win32::Security", :windows_only do
expect(Chef::ReservedNames::Win32::Security.has_admin_privileges?).to eq(true)
end
- # We've done some investigation adding a negative test and it turned
- # out to be a lot of work since mixlib-shellout doesn't have user
- # support for windows.
- #
- # TODO - Add negative tests once mixlib-shellout has user support
- it "has_admin_privileges? returns false when running as non-admin" do
- skip "requires user support in mixlib-shellout"
+ describe "running as non admin user" do
+ include Chef::Mixin::UserContext
+ let(:user) { "security_user" }
+ let(:password) { "Security@123" }
+
+ let(:domain) do
+ whoami = Mixlib::ShellOut.new("whoami")
+ whoami.run_command
+ whoami.error!
+ whoami.stdout.split("\\")[0]
+ end
+
+ before do
+ allow_any_instance_of(Chef::Mixin::UserContext).to receive(:node).and_return({ "platform_family" => "windows" })
+ add_user = Mixlib::ShellOut.new("net user #{user} #{password} /ADD")
+ add_user.run_command
+ add_user.error!
+ end
+
+ after do
+ delete_user = Mixlib::ShellOut.new("net user #{user} /delete")
+ delete_user.run_command
+ delete_user.error!
+ end
+
+ it "has_admin_privileges? returns false" do
+ has_admin_privileges = with_user_context(user, password, domain, :local) do
+ Chef::ReservedNames::Win32::Security.has_admin_privileges?
+ end
+ expect(has_admin_privileges).to eq(false)
+ end
end
describe "get_file_security" do
@@ -97,4 +123,87 @@ describe "Chef::Win32::Security", :windows_only do
end
end
end
+
+ describe ".get_token_information_elevation_type" do
+ let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_READ }
+
+ let(:token) do
+ Chef::ReservedNames::Win32::Security.open_process_token(
+ Chef::ReservedNames::Win32::Process.get_current_process,
+ token_rights)
+ end
+
+ context "when the token is valid" do
+ let(:token_elevation_type) { [:TokenElevationTypeDefault, :TokenElevationTypeFull, :TokenElevationTypeLimited] }
+
+ it "returns the token elevation type" do
+ elevation_type = Chef::ReservedNames::Win32::Security.get_token_information_elevation_type(token)
+ expect(token_elevation_type).to include(elevation_type)
+ end
+ end
+
+ context "when the token is invalid" do
+ it "raises `handle invalid` error" do
+ # If `OpenProcessToken` is stubbed, `open_process_token` returns an invalid token
+ allow(Chef::ReservedNames::Win32::Security).to receive(:OpenProcessToken).and_return(true)
+ expect { Chef::ReservedNames::Win32::Security.get_token_information_elevation_type(token) }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
+ end
+
+ describe ".get_account_right" do
+ let(:username) { ENV["USERNAME"] }
+
+ context "when given a valid username" do
+ it "returns an array of account right constants" do
+ Chef::ReservedNames::Win32::Security.add_account_right(username, "SeBatchLogonRight")
+ expect(Chef::ReservedNames::Win32::Security.get_account_right(username)).to include("SeBatchLogonRight")
+ end
+
+ it "passes an FFI::Pointer to LsaFreeMemory" do
+ Chef::ReservedNames::Win32::Security.add_account_right(username, "SeBatchLogonRight") # otherwise we return an empty array before LsaFreeMemory
+ expect(Chef::ReservedNames::Win32::Security).to receive(:LsaFreeMemory).with(instance_of(FFI::Pointer)).and_return(0) # not FFI::MemoryPointer
+ Chef::ReservedNames::Win32::Security.get_account_right(username)
+ end
+ end
+
+ context "when given an invalid username" do
+ let(:username) { "noooooooooope" }
+
+ it "raises an exception" do
+ expect { Chef::ReservedNames::Win32::Security.get_account_right(username) }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
+ end
+
+ describe ".remove_account_right" do
+ let(:username) { ENV["USERNAME"] }
+
+ context "when given a valid username" do
+ it "removes the account right constants" do
+ Chef::ReservedNames::Win32::Security.add_account_right(username, "SeBatchLogonRight")
+ expect(Chef::ReservedNames::Win32::Security.get_account_right(username)).to include("SeBatchLogonRight")
+ Chef::ReservedNames::Win32::Security.remove_account_right(username, "SeBatchLogonRight")
+ expect(Chef::ReservedNames::Win32::Security.get_account_right(username)).not_to include("SeBatchLogonRight")
+ end
+ end
+
+ context "when given an invalid username" do
+ let(:username) { "noooooooooope" }
+
+ it "raises an exception" do
+ expect { Chef::ReservedNames::Win32::Security.remove_account_right(username, "SeBatchLogonRight") }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
+ end
+
+ describe ".test_and_raise_lsa_nt_status" do
+ # NTSTATUS code: 0xC0000001 / STATUS_UNSUCCESSFUL
+ # Windows Error: ERROR_GEN_FAILURE / 31 / 0x1F / A device attached to the system is not functioning.
+ let(:status_unsuccessful) { 0xC0000001 }
+
+ it "raises an exception with the Win Error if the win32 result is not 0" do
+ expect { Chef::ReservedNames::Win32::Security.test_and_raise_lsa_nt_status(status_unsuccessful) }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
end
diff --git a/spec/functional/win32/versions_spec.rb b/spec/functional/win32/versions_spec.rb
index d6e840ed7f..19bd0e3875 100644
--- a/spec/functional/win32/versions_spec.rb
+++ b/spec/functional/win32/versions_spec.rb
@@ -21,7 +21,7 @@ if Chef::Platform.windows?
require "chef/win32/version"
end
-describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on_win2k3 do
+describe "Chef::ReservedNames::Win32::Version", :windows_only do
before do
wmi = WmiLite::Wmi.new
@@ -31,14 +31,12 @@ describe "Chef::ReservedNames::Win32::Version", :windows_only, :not_supported_on
# On Win2k8R2 and later, we can dynamically obtain marketing
# names for comparison from WMI so the test should not
# need to be modified when new Windows releases arise.
- # For Win2k3 and Win2k8, we use static names in this test
- # based on the version number information from WMI. The names
- # from WMI contain extended characters such as registered
- # trademark on Win2k8 and Win2k3 that we're not using in our
- # library, so we have to set the expectation statically.
- if Chef::Platform.windows_server_2003?
- @current_os_version = "Windows Server 2003 R2"
- elsif is_windows_server_2008?(host)
+ # For Win2k8 we use static names in this test based on the
+ # version number information from WMI. The names from WMI
+ # contain extended characters such as registered trademark
+ # on Win2k8 that we're not using in our library, so we have
+ # to set the expectation statically.
+ if is_windows_server_2008?(host)
@current_os_version = "Windows Server 2008"
else
# The name from WMI is actually what we want in Win2k8R2+.
diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb
index de12b8ba8e..4408c00b23 100644
--- a/spec/integration/client/client_spec.rb
+++ b/spec/integration/client/client_spec.rb
@@ -46,7 +46,7 @@ describe "chef-client" do
# we're running `chef-client` from the source tree and not the external one.
# cf. CHEF-4914
let(:chef_client) { "ruby '#{chef_dir}/chef-client' --minimal-ohai" }
- let(:chef_solo) { "ruby '#{chef_dir}/chef-solo' --minimal-ohai" }
+ let(:chef_solo) { "ruby '#{chef_dir}/chef-solo' --legacy-mode --minimal-ohai" }
let(:critical_env_vars) { %w{_ORIGINAL_GEM_PATH GEM_PATH GEM_HOME GEM_ROOT BUNDLE_BIN_PATH BUNDLE_GEMFILE RUBYLIB RUBYOPT RUBY_ENGINE RUBY_ROOT RUBY_VERSION PATH}.map { |o| "#{o}=#{ENV[o]}" } .join(" ") }
@@ -54,22 +54,22 @@ describe "chef-client" do
before { file "cookbooks/x/recipes/default.rb", "" }
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
end
- it "should complete successfully with no other environment variables", :skip => (Chef::Platform.windows?) do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ it "should complete successfully with no other environment variables", skip: (Chef::Platform.windows?) do
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
begin
- result = shell_out("env -i #{critical_env_vars} #{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("env -i #{critical_env_vars} #{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
result.error!
rescue
Chef::Log.info "Bare invocation will have the following load-path."
@@ -79,34 +79,34 @@ EOM
end
it "should complete successfully with --no-listen" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} --no-listen -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} --no-listen -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
it "should be able to node.save with bad utf8 characters in the node data" do
file "cookbooks/x/attributes/default.rb", 'default["badutf8"] = "Elan Ruusam\xE4e"'
- result = shell_out("#{chef_client} -z -r 'x::default' --disable-config", :cwd => path_to(""))
+ result = shell_out("#{chef_client} -z -r 'x::default' --disable-config", cwd: path_to(""))
result.error!
end
context "and no config file" do
it "should complete with success when cwd is just above cookbooks and paths are not specified" do
- result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to(""))
+ result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", cwd: path_to(""))
result.error!
end
it "should complete with success when cwd is below cookbooks and paths are not specified" do
- result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to("cookbooks/x"))
+ result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", cwd: path_to("cookbooks/x"))
result.error!
end
it "should fail when cwd is below high above and paths are not specified" do
- result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => File.expand_path("..", path_to("")))
+ result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", cwd: File.expand_path("..", path_to("")))
expect(result.exitstatus).to eq(1)
end
end
@@ -115,7 +115,7 @@ EOM
before { file ".chef/knife.rb", "xxx.xxx" }
it "should load .chef/knife.rb when -z is specified" do
- result = shell_out("#{chef_client} -z -o 'x::default'", :cwd => path_to(""))
+ result = shell_out("#{chef_client} -z -o 'x::default'", cwd: path_to(""))
# FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass
expect(result.stdout).to include("xxx")
end
@@ -123,79 +123,79 @@ EOM
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
context "and a private key" do
before do
- file "mykey.pem", <<EOM
------BEGIN RSA PRIVATE KEY-----
-MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
-0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
-NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
-0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
-AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
-HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
-8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
-zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
-k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
-i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
-G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
-ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
-awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
-7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
-g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
-Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
-HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
-V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
-fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
-lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
-c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
-fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
-YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
-syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
-+vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
------END RSA PRIVATE KEY-----
+ file "mykey.pem", <<~EOM
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
+ 0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
+ NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
+ 0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
+ AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
+ HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
+ 8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
+ zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
+ k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
+ i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
+ G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
+ ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
+ awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
+ 7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
+ g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
+ Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
+ HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
+ V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
+ fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
+ lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
+ c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
+ fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
+ YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
+ syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
+ +vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
+ -----END RSA PRIVATE KEY-----
EOM
end
it "should complete with success even with a client key" do
- file "config/client.rb", <<EOM
-local_mode true
-client_key #{path_to('mykey.pem').inspect}
-cookbook_path #{path_to('cookbooks').inspect}
+ file "config/client.rb", <<~EOM
+ local_mode true
+ client_key #{path_to('mykey.pem').inspect}
+ cookbook_path #{path_to('cookbooks').inspect}
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
result.error!
end
it "should run recipes specified directly on the command line" do
- file "config/client.rb", <<EOM
-local_mode true
-client_key #{path_to('mykey.pem').inspect}
-cookbook_path #{path_to('cookbooks').inspect}
+ file "config/client.rb", <<~EOM
+ local_mode true
+ client_key #{path_to('mykey.pem').inspect}
+ cookbook_path #{path_to('cookbooks').inspect}
EOM
- file "arbitrary.rb", <<EOM
-file #{path_to('tempfile.txt').inspect} do
- content '1'
-end
+ file "arbitrary.rb", <<~EOM
+ file #{path_to('tempfile.txt').inspect} do
+ content '1'
+ end
EOM
- file "arbitrary2.rb", <<EOM
-file #{path_to('tempfile2.txt').inspect} do
- content '2'
-end
+ file "arbitrary2.rb", <<~EOM
+ file #{path_to('tempfile2.txt').inspect} do
+ content '2'
+ end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" #{path_to('arbitrary.rb')} #{path_to('arbitrary2.rb')}", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" #{path_to('arbitrary.rb')} #{path_to('arbitrary2.rb')}", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -203,43 +203,43 @@ EOM
end
it "should run recipes specified as relative paths directly on the command line" do
- file "config/client.rb", <<EOM
-local_mode true
-client_key #{path_to('mykey.pem').inspect}
-cookbook_path #{path_to('cookbooks').inspect}
+ file "config/client.rb", <<~EOM
+ local_mode true
+ client_key #{path_to('mykey.pem').inspect}
+ cookbook_path #{path_to('cookbooks').inspect}
EOM
- file "arbitrary.rb", <<EOM
-file #{path_to('tempfile.txt').inspect} do
- content '1'
-end
+ file "arbitrary.rb", <<~EOM
+ file #{path_to('tempfile.txt').inspect} do
+ content '1'
+ end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" arbitrary.rb", :cwd => path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
end
it "should run recipes specified directly on the command line AFTER recipes in the run list" do
- file "config/client.rb", <<EOM
-local_mode true
-client_key #{path_to('mykey.pem').inspect}
-cookbook_path #{path_to('cookbooks').inspect}
+ file "config/client.rb", <<~EOM
+ local_mode true
+ client_key #{path_to('mykey.pem').inspect}
+ cookbook_path #{path_to('cookbooks').inspect}
EOM
- file "cookbooks/x/recipes/constant_definition.rb", <<EOM
-class ::Blah
- THECONSTANT = '1'
-end
+ file "cookbooks/x/recipes/constant_definition.rb", <<~EOM
+ class ::Blah
+ THECONSTANT = '1'
+ end
EOM
- file "arbitrary.rb", <<EOM
-file #{path_to('tempfile.txt').inspect} do
- content ::Blah::THECONSTANT
-end
+ file "arbitrary.rb", <<~EOM
+ file #{path_to('tempfile.txt').inspect} do
+ content ::Blah::THECONSTANT
+ end
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o x::constant_definition arbitrary.rb", :cwd => path_to(""))
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o x::constant_definition arbitrary.rb", cwd: path_to(""))
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("1")
@@ -248,74 +248,74 @@ EOM
end
it "should complete with success when passed the -z flag" do
- file "config/client.rb", <<EOM
-chef_server_url 'http://omg.com/blah'
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ chef_server_url 'http://omg.com/blah'
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
end
it "should complete with success when passed the --local-mode flag" do
- file "config/client.rb", <<EOM
-chef_server_url 'http://omg.com/blah'
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ chef_server_url 'http://omg.com/blah'
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", cwd: chef_dir)
result.error!
end
it "should not print SSL warnings when running in local-mode" do
- file "config/client.rb", <<EOM
-chef_server_url 'http://omg.com/blah'
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ chef_server_url 'http://omg.com/blah'
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", cwd: chef_dir)
expect(result.stdout).not_to include("SSL validation of HTTPS requests is disabled.")
result.error!
end
it "should complete with success when passed -z and --chef-zero-port" do
- file "config/client.rb", <<EOM
-chef_server_url 'http://omg.com/blah'
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ chef_server_url 'http://omg.com/blah'
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
end
it "should complete with success when setting the run list with -r" do
- file "config/client.rb", <<EOM
-chef_server_url 'http://omg.com/blah'
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ chef_server_url 'http://omg.com/blah'
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -r 'x::default' -z -l info", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -r 'x::default' -z -l info", cwd: chef_dir)
expect(result.stdout).not_to include("Overridden Run List")
expect(result.stdout).to include("Run List is [recipe[x::default]]")
result.error!
end
- it "should complete with success when using --profile-ruby and output a profile file" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ it "should complete with success when using --profile-ruby and output a profile file", :not_supported_on_aix do
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z --profile-ruby", :cwd => chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z --profile-ruby", cwd: chef_dir)
result.error!
expect(File.exist?(path_to("config/local-mode-cache/cache/graph_profile.out"))).to be true
end
it "doesn't produce a profile when --profile-ruby is not present" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", :cwd => chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", cwd: chef_dir)
result.error!
expect(File.exist?(path_to("config/local-mode-cache/cache/graph_profile.out"))).to be false
end
@@ -324,18 +324,18 @@ EOM
when_the_repository "has a cookbook that should fail chef_version checks" do
before do
file "cookbooks/x/recipes/default.rb", ""
- file "cookbooks/x/metadata.rb", <<EOM
-name 'x'
-version '0.0.1'
-chef_version '~> 999.99'
+ file "cookbooks/x/metadata.rb", <<~EOM
+ name 'x'
+ version '0.0.1'
+ chef_version '~> 999.99'
EOM
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
end
it "should fail the chef client run" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
expect(command.exitstatus).to eql(1)
expect(command.stdout).to match(/Chef::Exceptions::CookbookChefVersionMismatch/)
end
@@ -361,7 +361,7 @@ EOM
end
it "the cheffish DSL is loaded lazily" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
expect(command.exitstatus).to eql(0)
end
end
@@ -380,7 +380,7 @@ EOM
it "the cheffish DSL tries to load but fails (because chef-provisioning is not there)" do
# we'd need to have a custom bundle to fix this that omitted chef-provisioning, but that would dig our crazy even deeper, so lets not
skip "but if chef-provisioning is in our bundle or in our gemset then this test, very annoyingly, always fails"
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
expect(command.exitstatus).to eql(1)
expect(command.stdout).to match(/cannot load such file -- chef\/provisioning/)
end
@@ -405,17 +405,17 @@ EOM
end
it "should output each deprecation warning only once, at the end of the run" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-# Mimick what happens when you are on the console
-formatters << :doc
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ # Mimick what happens when you are on the console
+ formatters << :doc
+ log_level :warn
EOM
ENV.delete("CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS")
- result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir)
+ result = shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
expect(result.error?).to be_falsey
# Search to the end of the client run in the output
@@ -430,37 +430,37 @@ EOM
when_the_repository "has a cookbook with only an audit recipe" do
before do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-audit_mode :enabled
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ audit_mode :enabled
EOM
end
it "should exit with a zero code when there is not an audit failure" do
- file "cookbooks/audit_test/recipes/succeed.rb", <<-RECIPE
-control_group "control group without top level control" do
- it "should succeed" do
- expect(2 - 2).to eq(0)
- end
-end
+ file "cookbooks/audit_test/recipes/succeed.rb", <<~RECIPE
+ control_group "control group without top level control" do
+ it "should succeed" do
+ expect(2 - 2).to eq(0)
+ end
+ end
RECIPE
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'audit_test::succeed' -l info", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'audit_test::succeed' -l info", cwd: chef_dir)
expect(result.error?).to be_falsey
expect(result.stdout).to include("Successfully executed all `control_group` blocks and contained examples")
end
it "should exit with a non-zero code when there is an audit failure" do
- file "cookbooks/audit_test/recipes/fail.rb", <<-RECIPE
-control_group "control group without top level control" do
- it "should fail" do
- expect(2 - 2).to eq(1)
- end
-end
+ file "cookbooks/audit_test/recipes/fail.rb", <<~RECIPE
+ control_group "control group without top level control" do
+ it "should fail" do
+ expect(2 - 2).to eq(1)
+ end
+ end
RECIPE
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'audit_test::fail'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'audit_test::fail'", cwd: chef_dir)
expect(result.error?).to be_truthy
expect(result.stdout).to include("Failure/Error: expect(2 - 2).to eq(1)")
end
@@ -468,26 +468,26 @@ end
when_the_repository "has a cookbook that deploys a file" do
before do
- file "cookbooks/x/recipes/default.rb", <<-RECIPE
-cookbook_file #{path_to('tempfile.txt').inspect} do
- source "my_file"
-end
+ file "cookbooks/x/recipes/default.rb", <<~RECIPE
+ cookbook_file #{path_to('tempfile.txt').inspect} do
+ source "my_file"
+ end
RECIPE
- file "cookbooks/x/files/my_file", <<-FILE
-this is my file
+ file "cookbooks/x/files/my_file", <<~FILE
+ this is my file
FILE
end
[true, false].each do |lazy|
context "with no_lazy_load set to #{lazy}" do
it "should create the file" do
- file "config/client.rb", <<EOM
-no_lazy_load #{lazy}
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ no_lazy_load #{lazy}
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
- result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt")).strip).to eq("this is my file")
@@ -498,10 +498,10 @@ EOM
when_the_repository "has a cookbook with an ohai plugin" do
before do
- file "cookbooks/x/recipes/default.rb", <<-RECIPE
-file #{path_to('tempfile.txt').inspect} do
- content node["english"]["version"]
-end
+ file "cookbooks/x/recipes/default.rb", <<~RECIPE
+ file #{path_to('tempfile.txt').inspect} do
+ content node["english"]["version"]
+ end
RECIPE
file "cookbooks/x/ohai/english.rb", <<-OHAI
@@ -515,14 +515,14 @@ end
end
OHAI
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
end
it "should run the ohai plugin" do
- result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -l debug -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
result.error!
expect(IO.read(path_to("tempfile.txt"))).to eq("2014")
@@ -542,15 +542,21 @@ EOM
let(:tmp_dir) { Dir.mktmpdir("recipe-url") }
it "should complete with success when passed -z and --recipe-url" do
- file "config/client.rb", <<EOM
-chef_repo_path "#{tmp_dir}"
+ file "config/client.rb", <<~EOM
+ chef_repo_path "#{tmp_dir}"
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --recipe-url=http://localhost:9000/recipes.tgz -o 'x::default' -z", :cwd => tmp_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --recipe-url=http://localhost:9000/recipes.tgz -o 'x::default' -z", cwd: tmp_dir)
result.error!
end
it "should fail when passed --recipe-url and not passed -z" do
- result = shell_out("#{chef_client} --recipe-url=http://localhost:9000/recipes.tgz", :cwd => tmp_dir)
+ result = shell_out("#{chef_client} --recipe-url=http://localhost:9000/recipes.tgz", cwd: tmp_dir)
+ expect(result.exitstatus).not_to eq(0)
+ end
+
+ it "should fail when passed --recipe-url with a file that doesn't exist" do
+ broken_path = File.join(CHEF_SPEC_DATA, "recipes_dont_exist.tgz")
+ result = shell_out("#{chef_client} --recipe-url=#{broken_path}", cwd: tmp_dir)
expect(result.exitstatus).not_to eq(0)
end
end
@@ -558,31 +564,31 @@ EOM
when_the_repository "has a cookbook with broken metadata.rb, but has metadata.json" do
before do
file "cookbooks/x/recipes/default.rb", ""
- file "cookbooks/x/metadata.rb", <<EOM
-name 'x'
-version '0.0.1'
-raise "TEH SADNESS"
+ file "cookbooks/x/metadata.rb", <<~EOM
+ name 'x'
+ version '0.0.1'
+ raise "TEH SADNESS"
EOM
- file "cookbooks/x/metadata.json", <<EOM
-{
- "name": "x",
- "version": "0.0.1"
-}
+ file "cookbooks/x/metadata.json", <<~EOM
+ {
+ "name": "x",
+ "version": "0.0.1"
+ }
EOM
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
end
it "the chef client run should succeed" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
end
it "a chef-solo run should succeed" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
end
end
@@ -594,34 +600,132 @@ EOM
level :info
end
EOM
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
end
it "a chef client run should not log to info by default" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef client run to a pipe should not log to info by default" do
- command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", :cwd => chef_dir)
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef solo run should not log to info by default" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", :cwd => chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
it "a chef solo run to a pipe should not log to info by default" do
- command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", :cwd => chef_dir)
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork | tee #{path_to('chefrun.out')}", cwd: chef_dir)
command.error!
expect(command.stdout).not_to include("INFO")
end
end
+
+ when_the_repository "has a cookbook that knows if we're running forked" do
+ before do
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ puts Chef::Config[:client_fork] ? "WITHFORK" : "NOFORK"
+EOM
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+EOM
+ end
+
+ it "chef-client runs by default with no supervisor" do
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+
+ it "chef-solo runs by default with no supervisor" do
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+
+ it "chef-client --no-fork does not fork" do
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+
+ it "chef-solo --no-fork does not fork" do
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --no-fork", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+
+ it "chef-client with --fork uses a supervisor" do
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --fork", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("WITHFORK")
+ end
+
+ it "chef-solo with --fork uses a supervisor" do
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --fork", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("WITHFORK")
+ end
+ end
+
+ when_the_repository "has a cookbook that knows if we're running forked, and configures forking in config.rb" do
+ before do
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ puts Chef::Config[:client_fork] ? "WITHFORK" : "NOFORK"
+EOM
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ client_fork true
+EOM
+ end
+
+ it "chef-client uses a supervisor" do
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("WITHFORK")
+ end
+
+ it "chef-solo uses a supervisor" do
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("WITHFORK")
+ end
+ end
+
+ when_the_repository "has a cookbook that knows if we're running forked, and configures no-forking in config.rb" do
+ before do
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ puts Chef::Config[:client_fork] ? "WITHFORK" : "NOFORK"
+EOM
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ client_fork false
+EOM
+ end
+
+ it "chef-client uses a supervisor" do
+ command = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+
+ it "chef-solo uses a supervisor" do
+ command = shell_out("#{chef_solo} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", cwd: chef_dir)
+ command.error!
+ expect(command.stdout).to include("NOFORK")
+ end
+ end
end
diff --git a/spec/integration/client/exit_code_spec.rb b/spec/integration/client/exit_code_spec.rb
index 4397426723..7352863dbf 100644
--- a/spec/integration/client/exit_code_spec.rb
+++ b/spec/integration/client/exit_code_spec.rb
@@ -28,24 +28,24 @@ describe "chef-client" do
when_the_repository "uses RFC 062 defined exit codes" do
def setup_client_rb
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
EOM
end
def setup_client_rb_with_audit_mode
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-audit_mode :audit_only
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ audit_mode :audit_only
EOM
end
def run_chef_client_and_expect_exit_code(exit_code)
shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'",
- :cwd => chef_dir,
- :returns => [exit_code])
+ cwd: chef_dir,
+ returns: [exit_code])
end
context "has a cookbook" do
@@ -66,12 +66,12 @@ EOM
context "with an audit recipe" do
context "which fails" do
before do
- file "cookbooks/x/recipes/default.rb", <<-RECIPE
-control_group "control group without top level control" do
- it "should fail" do
- expect(4 - 4).to eq(1)
- end
-end
+ file "cookbooks/x/recipes/default.rb", <<~RECIPE
+ control_group "control group without top level control" do
+ it "should fail" do
+ expect(4 - 4).to eq(1)
+ end
+ end
RECIPE
end
@@ -112,8 +112,8 @@ RECIPE
context "when a reboot exception is raised (like from the reboot resource)" do
before do
- file "cookbooks/x/recipes/default.rb", <<EOM
-raise Chef::Exceptions::Reboot.new
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ raise Chef::Exceptions::Reboot.new
EOM
end
@@ -125,8 +125,8 @@ EOM
context "when an attempt to reboot fails (like from the reboot resource)" do
before do
- file "cookbooks/x/recipes/default.rb", <<EOM
-raise Chef::Exceptions::RebootFailed.new
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ raise Chef::Exceptions::RebootFailed.new
EOM
end
diff --git a/spec/integration/client/ipv6_spec.rb b/spec/integration/client/ipv6_spec.rb
index 68c58bb8ea..c3cb73e4fa 100644
--- a/spec/integration/client/ipv6_spec.rb
+++ b/spec/integration/client/ipv6_spec.rb
@@ -22,37 +22,37 @@ describe "chef-client" do
include IntegrationSupport
include Chef::Mixin::ShellOut
- let(:chef_zero_opts) { { :host => "::1" } }
+ let(:chef_zero_opts) { { host: "::1" } }
let(:validation_pem) do
- <<-END_VALIDATION_PEM
------BEGIN RSA PRIVATE KEY-----
-MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
-0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
-NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
-0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
-AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
-HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
-8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
-zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
-k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
-i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
-G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
-ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
-awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
-7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
-g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
-Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
-HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
-V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
-fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
-lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
-c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
-fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
-YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
-syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
-+vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
------END RSA PRIVATE KEY-----
+ <<~END_VALIDATION_PEM
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
+ 0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
+ NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
+ 0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
+ AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
+ HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
+ 8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
+ zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
+ k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
+ i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
+ G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
+ ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
+ awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
+ 7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
+ g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
+ Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
+ HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
+ V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
+ fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
+ lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
+ c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
+ fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
+ YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
+ syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
+ +vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
+ -----END RSA PRIVATE KEY-----
END_VALIDATION_PEM
end
@@ -61,11 +61,11 @@ END_VALIDATION_PEM
end
let(:basic_config_file) do
- <<-END_CLIENT_RB
-chef_server_url "http://[::1]:8900"
-validation_key '#{path_to('config/validator.pem')}'
-cache_path '#{cache_path}'
-client_key '#{cache_path}/client.pem'
+ <<~END_CLIENT_RB
+ chef_server_url "http://[::1]:8900"
+ validation_key '#{path_to('config/validator.pem')}'
+ cache_path '#{cache_path}'
+ client_key '#{cache_path}/client.pem'
END_CLIENT_RB
end
@@ -83,7 +83,7 @@ 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_chef_server "is running on IPv6", :not_supported_on_solaris, :not_supported_on_gce, :not_supported_on_aix do
when_the_repository "has a cookbook with a no-op recipe" do
before do
@@ -93,7 +93,7 @@ END_CLIENT_RB
end
it "should complete with success" do
- result = shell_out("#{chef_client_cmd} -o 'noop::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client_cmd} -o 'noop::default'", cwd: chef_dir)
result.error!
end
@@ -125,7 +125,7 @@ END_CLIENT_RB
end
it "should complete with success" do
- result = shell_out("#{chef_client_cmd} -o 'api-smoke-test::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client_cmd} -o 'api-smoke-test::default'", cwd: chef_dir)
result.error!
end
diff --git a/spec/integration/knife/chef_fs_data_store_spec.rb b/spec/integration/knife/chef_fs_data_store_spec.rb
index 02508b799d..79b0307e0d 100644
--- a/spec/integration/knife/chef_fs_data_store_spec.rb
+++ b/spec/integration/knife/chef_fs_data_store_spec.rb
@@ -54,59 +54,59 @@ describe "ChefFSDataStore tests", :workstation do
context "GET /TYPE" do
it "knife list -z -R returns everything" do
- knife("list -z -Rfp /").should_succeed <<EOM
-/acls/
-/acls/clients/
-/acls/clients/x.json
-/acls/containers/
-/acls/containers/x.json
-/acls/cookbook_artifacts/
-/acls/cookbook_artifacts/x.json
-/acls/cookbooks/
-/acls/cookbooks/x.json
-/acls/data_bags/
-/acls/data_bags/x.json
-/acls/environments/
-/acls/environments/x.json
-/acls/groups/
-/acls/groups/x.json
-/acls/nodes/
-/acls/nodes/x.json
-/acls/organization.json
-/acls/policies/
-/acls/policies/x.json
-/acls/policy_groups/
-/acls/policy_groups/x.json
-/acls/roles/
-/acls/roles/x.json
-/clients/
-/clients/x.json
-/containers/
-/containers/x.json
-/cookbook_artifacts/
-/cookbook_artifacts/x-111/
-/cookbook_artifacts/x-111/metadata.rb
-/cookbooks/
-/cookbooks/x/
-/cookbooks/x/metadata.rb
-/data_bags/
-/data_bags/x/
-/data_bags/x/y.json
-/environments/
-/environments/x.json
-/groups/
-/groups/x.json
-/invitations.json
-/members.json
-/nodes/
-/nodes/x.json
-/org.json
-/policies/
-/policies/x-111.json
-/policy_groups/
-/policy_groups/x.json
-/roles/
-/roles/x.json
+ knife("list -z -Rfp /").should_succeed <<~EOM
+ /acls/
+ /acls/clients/
+ /acls/clients/x.json
+ /acls/containers/
+ /acls/containers/x.json
+ /acls/cookbook_artifacts/
+ /acls/cookbook_artifacts/x.json
+ /acls/cookbooks/
+ /acls/cookbooks/x.json
+ /acls/data_bags/
+ /acls/data_bags/x.json
+ /acls/environments/
+ /acls/environments/x.json
+ /acls/groups/
+ /acls/groups/x.json
+ /acls/nodes/
+ /acls/nodes/x.json
+ /acls/organization.json
+ /acls/policies/
+ /acls/policies/x.json
+ /acls/policy_groups/
+ /acls/policy_groups/x.json
+ /acls/roles/
+ /acls/roles/x.json
+ /clients/
+ /clients/x.json
+ /containers/
+ /containers/x.json
+ /cookbook_artifacts/
+ /cookbook_artifacts/x-111/
+ /cookbook_artifacts/x-111/metadata.rb
+ /cookbooks/
+ /cookbooks/x/
+ /cookbooks/x/metadata.rb
+ /data_bags/
+ /data_bags/x/
+ /data_bags/x/y.json
+ /environments/
+ /environments/x.json
+ /groups/
+ /groups/x.json
+ /invitations.json
+ /members.json
+ /nodes/
+ /nodes/x.json
+ /org.json
+ /policies/
+ /policies/x-111.json
+ /policy_groups/
+ /policy_groups/x.json
+ /roles/
+ /roles/x.json
EOM
end
end
@@ -190,9 +190,9 @@ EOM
end
it "knife cookbook upload works" do
- knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} x").should_succeed :stderr => <<EOM
-Uploading x [1.0.0]
-Uploaded 1 cookbook.
+ knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} x").should_succeed stderr: <<~EOM
+ Uploading x [1.0.0]
+ Uploaded 1 cookbook.
EOM
knife("list --local -Rfp /cookbooks").should_succeed "/cookbooks/x/\n/cookbooks/x/metadata.rb\n"
end
@@ -218,13 +218,13 @@ EOM
knife("list --local /roles").should_succeed "/roles/x.json\n"
end
- it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty", :skip => (RUBY_VERSION < "1.9") do
+ it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty", skip: (RUBY_VERSION < "1.9") do
knife("raw -z -i #{path_to('rolestuff.json')} -m PUT /roles/x").should_succeed( /"x"/ )
- expect(IO.read(path_to("roles/x.json"))).to eq <<EOM.strip
-{
- "name": "x",
- "description": "hi there"
-}
+ expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
+ {
+ "name": "x",
+ "description": "hi there"
+ }
EOM
end
end
@@ -247,9 +247,9 @@ EOM
end
it "knife cookbook upload works" do
- knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} z").should_succeed :stderr => <<EOM
-Uploading z [1.0.0]
-Uploaded 1 cookbook.
+ knife("cookbook upload -z --cookbook-path #{path_to('cookbooks_to_upload')} z").should_succeed stderr: <<~EOM
+ Uploading z [1.0.0]
+ Uploaded 1 cookbook.
EOM
knife("list --local -Rfp /cookbooks").should_succeed "/cookbooks/z/\n/cookbooks/z/metadata.rb\n"
end
@@ -281,46 +281,46 @@ EOM
knife("list --local /roles").should_succeed "/roles/z.json\n"
end
- it "After knife raw -z -i rolestuff.json -m POST /roles, the output is pretty", :skip => (RUBY_VERSION < "1.9") do
+ it "After knife raw -z -i rolestuff.json -m POST /roles, the output is pretty", skip: (RUBY_VERSION < "1.9") do
knife("raw -z -i #{path_to('rolestuff.json')} -m POST /roles").should_succeed( /uri/ )
- expect(IO.read(path_to("roles/x.json"))).to eq <<EOM.strip
-{
- "name": "x",
- "description": "hi there"
-}
+ expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
+ {
+ "name": "x",
+ "description": "hi there"
+ }
EOM
end
end
it "knife list -z -R returns nothing" do
- knife("list -z -Rfp /").should_succeed <<EOM
-/acls/
-/acls/clients/
-/acls/containers/
-/acls/cookbook_artifacts/
-/acls/cookbooks/
-/acls/data_bags/
-/acls/environments/
-/acls/groups/
-/acls/nodes/
-/acls/organization.json
-/acls/policies/
-/acls/policy_groups/
-/acls/roles/
-/clients/
-/containers/
-/cookbook_artifacts/
-/cookbooks/
-/data_bags/
-/environments/
-/groups/
-/invitations.json
-/members.json
-/nodes/
-/org.json
-/policies/
-/policy_groups/
-/roles/
+ knife("list -z -Rfp /").should_succeed <<~EOM
+ /acls/
+ /acls/clients/
+ /acls/containers/
+ /acls/cookbook_artifacts/
+ /acls/cookbooks/
+ /acls/data_bags/
+ /acls/environments/
+ /acls/groups/
+ /acls/nodes/
+ /acls/organization.json
+ /acls/policies/
+ /acls/policy_groups/
+ /acls/roles/
+ /clients/
+ /containers/
+ /cookbook_artifacts/
+ /cookbooks/
+ /data_bags/
+ /environments/
+ /groups/
+ /invitations.json
+ /members.json
+ /nodes/
+ /org.json
+ /policies/
+ /policy_groups/
+ /roles/
EOM
end
@@ -442,23 +442,23 @@ EOM
context "GET /TYPE" do
it "knife list -z -R returns everything" do
- knife("list -z -Rfp /").should_succeed <<EOM
-/clients/
-/clients/x.json
-/cookbooks/
-/cookbooks/x/
-/cookbooks/x/metadata.rb
-/data_bags/
-/data_bags/x/
-/data_bags/x/y.json
-/environments/
-/environments/x.json
-/nodes/
-/nodes/x.json
-/roles/
-/roles/x.json
-/users/
-/users/x.json
+ knife("list -z -Rfp /").should_succeed <<~EOM
+ /clients/
+ /clients/x.json
+ /cookbooks/
+ /cookbooks/x/
+ /cookbooks/x/metadata.rb
+ /data_bags/
+ /data_bags/x/
+ /data_bags/x/y.json
+ /environments/
+ /environments/x.json
+ /nodes/
+ /nodes/x.json
+ /roles/
+ /roles/x.json
+ /users/
+ /users/x.json
EOM
end
end
@@ -489,13 +489,13 @@ EOM
knife("list --local /users").should_succeed "/users/x.json\n"
end
- it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty", :skip => (RUBY_VERSION < "1.9") do
+ it "After knife raw -z -i rolestuff.json -m PUT /roles/x, the output is pretty", skip: (RUBY_VERSION < "1.9") do
knife("raw -z -i #{path_to('rolestuff.json')} -m PUT /roles/x").should_succeed( /"x"/ )
- expect(IO.read(path_to("roles/x.json"))).to eq <<EOM.strip
-{
- "name": "x",
- "description": "hi there"
-}
+ expect(IO.read(path_to("roles/x.json"))).to eq <<~EOM.strip
+ {
+ "name": "x",
+ "description": "hi there"
+ }
EOM
end
end
@@ -519,14 +519,14 @@ EOM
end
it "knife list -z -R returns nothing" do
- knife("list -z -Rfp /").should_succeed <<EOM
-/clients/
-/cookbooks/
-/data_bags/
-/environments/
-/nodes/
-/roles/
-/users/
+ knife("list -z -Rfp /").should_succeed <<~EOM
+ /clients/
+ /cookbooks/
+ /data_bags/
+ /environments/
+ /nodes/
+ /roles/
+ /users/
EOM
end
diff --git a/spec/integration/knife/chef_repo_path_spec.rb b/spec/integration/knife/chef_repo_path_spec.rb
index e609fa60b3..9df0b9def9 100644
--- a/spec/integration/knife/chef_repo_path_spec.rb
+++ b/spec/integration/knife/chef_repo_path_spec.rb
@@ -59,92 +59,92 @@ describe "chef_repo_path tests", :workstation do
it "knife list --local -Rfp --chef-repo-path chef_repo2 / grabs chef_repo2 stuff" do
Chef::Config.delete(:chef_repo_path)
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<EOM
-/clients/
-/clients/client3.json
-/cookbooks/
-/cookbooks/cookbook3/
-/cookbooks/cookbook3/metadata.rb
-/data_bags/
-/data_bags/bag3/
-/data_bags/bag3/item3.json
-/environments/
-/environments/env3.json
-/nodes/
-/nodes/node3.json
-/roles/
-/roles/role3.json
-/users/
-/users/user3.json
+ knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<~EOM
+ /clients/
+ /clients/client3.json
+ /cookbooks/
+ /cookbooks/cookbook3/
+ /cookbooks/cookbook3/metadata.rb
+ /data_bags/
+ /data_bags/bag3/
+ /data_bags/bag3/item3.json
+ /environments/
+ /environments/env3.json
+ /nodes/
+ /nodes/node3.json
+ /roles/
+ /roles/role3.json
+ /users/
+ /users/user3.json
EOM
end
it "knife list --local -Rfp --chef-repo-path chef_r~1 / grabs chef_repo2 stuff", :windows_only do
Chef::Config.delete(:chef_repo_path)
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<EOM
-/clients/
-/clients/client3.json
-/cookbooks/
-/cookbooks/cookbook3/
-/cookbooks/cookbook3/metadata.rb
-/data_bags/
-/data_bags/bag3/
-/data_bags/bag3/item3.json
-/environments/
-/environments/env3.json
-/nodes/
-/nodes/node3.json
-/roles/
-/roles/role3.json
-/users/
-/users/user3.json
+ knife("list --local -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<~EOM
+ /clients/
+ /clients/client3.json
+ /cookbooks/
+ /cookbooks/cookbook3/
+ /cookbooks/cookbook3/metadata.rb
+ /data_bags/
+ /data_bags/bag3/
+ /data_bags/bag3/item3.json
+ /environments/
+ /environments/env3.json
+ /nodes/
+ /nodes/node3.json
+ /roles/
+ /roles/role3.json
+ /users/
+ /users/user3.json
EOM
end
it "knife list --local -Rfp --chef-repo-path chef_r~1 / grabs chef_repo2 stuff", :windows_only do
Chef::Config.delete(:chef_repo_path)
- knife("list -z -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<EOM
-/acls/
-/acls/clients/
-/acls/clients/client3.json
-/acls/containers/
-/acls/cookbook_artifacts/
-/acls/cookbooks/
-/acls/cookbooks/cookbook3.json
-/acls/data_bags/
-/acls/data_bags/bag3.json
-/acls/environments/
-/acls/environments/env3.json
-/acls/groups/
-/acls/nodes/
-/acls/nodes/node3.json
-/acls/organization.json
-/acls/policies/
-/acls/policy_groups/
-/acls/roles/
-/acls/roles/role3.json
-/clients/
-/clients/client3.json
-/containers/
-/cookbook_artifacts/
-/cookbooks/
-/cookbooks/cookbook3/
-/cookbooks/cookbook3/metadata.rb
-/data_bags/
-/data_bags/bag3/
-/data_bags/bag3/item3.json
-/environments/
-/environments/env3.json
-/groups/
-/invitations.json
-/members.json
-/nodes/
-/nodes/node3.json
-/org.json
-/policies/
-/policy_groups/
-/roles/
-/roles/role3.json
+ knife("list -z -Rfp --chef-repo-path #{path_to('chef_r~1')} /").should_succeed <<~EOM
+ /acls/
+ /acls/clients/
+ /acls/clients/client3.json
+ /acls/containers/
+ /acls/cookbook_artifacts/
+ /acls/cookbooks/
+ /acls/cookbooks/cookbook3.json
+ /acls/data_bags/
+ /acls/data_bags/bag3.json
+ /acls/environments/
+ /acls/environments/env3.json
+ /acls/groups/
+ /acls/nodes/
+ /acls/nodes/node3.json
+ /acls/organization.json
+ /acls/policies/
+ /acls/policy_groups/
+ /acls/roles/
+ /acls/roles/role3.json
+ /clients/
+ /clients/client3.json
+ /containers/
+ /cookbook_artifacts/
+ /cookbooks/
+ /cookbooks/cookbook3/
+ /cookbooks/cookbook3/metadata.rb
+ /data_bags/
+ /data_bags/bag3/
+ /data_bags/bag3/item3.json
+ /environments/
+ /environments/env3.json
+ /groups/
+ /invitations.json
+ /members.json
+ /nodes/
+ /nodes/node3.json
+ /org.json
+ /policies/
+ /policy_groups/
+ /roles/
+ /roles/role3.json
EOM
end
@@ -157,23 +157,23 @@ EOM
end
it "knife list --local -Rfp --chef-repo-path chef_repo2 / grabs chef_repo2 stuff" do
- knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<EOM
-/clients/
-/clients/client3.json
-/cookbooks/
-/cookbooks/cookbook3/
-/cookbooks/cookbook3/metadata.rb
-/data_bags/
-/data_bags/bag3/
-/data_bags/bag3/item3.json
-/environments/
-/environments/env3.json
-/nodes/
-/nodes/node3.json
-/roles/
-/roles/role3.json
-/users/
-/users/user3.json
+ knife("list --local -Rfp --chef-repo-path #{path_to('chef_repo2')} /").should_succeed <<~EOM
+ /clients/
+ /clients/client3.json
+ /cookbooks/
+ /cookbooks/cookbook3/
+ /cookbooks/cookbook3/metadata.rb
+ /data_bags/
+ /data_bags/bag3/
+ /data_bags/bag3/item3.json
+ /environments/
+ /environments/env3.json
+ /nodes/
+ /nodes/node3.json
+ /roles/
+ /roles/role3.json
+ /users/
+ /users/user3.json
EOM
end
@@ -194,23 +194,23 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client2.json
-cookbooks/
-cookbooks/cookbook2/
-cookbooks/cookbook2/metadata.rb
-data_bags/
-data_bags/bag2/
-data_bags/bag2/item2.json
-environments/
-environments/env2.json
-nodes/
-nodes/node2.json
-roles/
-roles/role2.json
-users/
-users/user2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client2.json
+ cookbooks/
+ cookbooks/cookbook2/
+ cookbooks/cookbook2/metadata.rb
+ data_bags/
+ data_bags/bag2/
+ data_bags/bag2/item2.json
+ environments/
+ environments/env2.json
+ nodes/
+ nodes/node2.json
+ roles/
+ roles/role2.json
+ users/
+ users/user2.json
EOM
end
end
@@ -218,9 +218,9 @@ EOM
context "when cwd is inside data_bags2" do
before { cwd "data_bags2" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag2/
-bag2/item2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag2/
+ bag2/item2.json
EOM
end
it "knife list --local -Rfp ../roles lists roles" do
@@ -239,23 +239,23 @@ EOM
context "when cwd is at the top level" do
before { cwd "." }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client2.json
-cookbooks/
-cookbooks/cookbook2/
-cookbooks/cookbook2/metadata.rb
-data_bags/
-data_bags/bag2/
-data_bags/bag2/item2.json
-environments/
-environments/env2.json
-nodes/
-nodes/node2.json
-roles/
-roles/role2.json
-users/
-users/user2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client2.json
+ cookbooks/
+ cookbooks/cookbook2/
+ cookbooks/cookbook2/metadata.rb
+ data_bags/
+ data_bags/bag2/
+ data_bags/bag2/item2.json
+ environments/
+ environments/env2.json
+ nodes/
+ nodes/node2.json
+ roles/
+ roles/role2.json
+ users/
+ users/user2.json
EOM
end
end
@@ -277,9 +277,9 @@ EOM
context "when cwd is inside data_bags2" do
before { cwd "data_bags2" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag2/
-bag2/item2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag2/
+ bag2/item2.json
EOM
end
end
@@ -310,23 +310,23 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client3.json
-cookbooks/
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env3.json
-nodes/
-nodes/node3.json
-roles/
-roles/role3.json
-users/
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env3.json
+ nodes/
+ nodes/node3.json
+ roles/
+ roles/role3.json
+ users/
+ users/user3.json
EOM
end
end
@@ -334,9 +334,9 @@ EOM
context "when cwd is inside chef_repo2/data_bags" do
before { cwd "chef_repo2/data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -359,11 +359,11 @@ EOM
file "clients2/blah.json", {}
end
it "knife show /clients/blah.json succeeds" do
- knife("show --local /clients/blah.json").should_succeed <<EOM
-/clients/blah.json:
-{
+ knife("show --local /clients/blah.json").should_succeed <<~EOM
+ /clients/blah.json:
+ {
-}
+ }
EOM
end
end
@@ -374,13 +374,13 @@ EOM
file "cookbooks2/blah/metadata.rb", ""
end
it "knife list -Rfp cookbooks shows files in blah" do
- knife("list --local -Rfp /cookbooks").should_succeed <<EOM
-/cookbooks/blah/
-/cookbooks/blah/metadata.rb
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
+ knife("list --local -Rfp /cookbooks").should_succeed <<~EOM
+ /cookbooks/blah/
+ /cookbooks/blah/metadata.rb
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
EOM
end
end
@@ -391,13 +391,13 @@ EOM
file "cookbooks2/blah/metadata.rb", ""
end
it "knife list -Rfp cookbooks shows files in blah" do
- knife("list --local -Rfp /cookbooks").should_succeed(<<EOM, :stderr => "WARN: Cookbook 'blah' is empty or entirely chefignored at #{Chef::Config.cookbook_path[0]}/blah\n")
-/cookbooks/blah/
-/cookbooks/blah/metadata.rb
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
+ knife("list --local -Rfp /cookbooks").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'blah' is empty or entirely chefignored at #{Chef::Config.cookbook_path[0]}/blah\n")
+ /cookbooks/blah/
+ /cookbooks/blah/metadata.rb
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
EOM
end
end
@@ -408,13 +408,13 @@ EOM
file "cookbooks2/blah/metadata.rb", ""
end
it "knife list -Rfp cookbooks shows files in the first cookbook and not the second" do
- knife("list --local -Rfp /cookbooks").should_succeed(<<EOM, :stderr => "WARN: Child with name 'blah' found in multiple directories: #{Chef::Config.cookbook_path[0]}/blah and #{Chef::Config.cookbook_path[1]}/blah\n")
-/cookbooks/blah/
-/cookbooks/blah/metadata.json
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
+ knife("list --local -Rfp /cookbooks").should_succeed(<<~EOM, stderr: "WARN: Child with name 'blah' found in multiple directories: #{Chef::Config.cookbook_path[0]}/blah and #{Chef::Config.cookbook_path[1]}/blah\n")
+ /cookbooks/blah/
+ /cookbooks/blah/metadata.json
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
EOM
end
end
@@ -425,13 +425,13 @@ EOM
file "data_bags2/blah/item.json", ""
end
it "knife list -Rfp data_bags shows files in blah" do
- knife("list --local -Rfp /data_bags").should_succeed <<EOM
-/data_bags/bag/
-/data_bags/bag/item.json
-/data_bags/bag2/
-/data_bags/bag2/item2.json
-/data_bags/blah/
-/data_bags/blah/item.json
+ knife("list --local -Rfp /data_bags").should_succeed <<~EOM
+ /data_bags/bag/
+ /data_bags/bag/item.json
+ /data_bags/bag2/
+ /data_bags/bag2/item2.json
+ /data_bags/blah/
+ /data_bags/blah/item.json
EOM
end
end
@@ -442,13 +442,13 @@ EOM
file "data_bags2/blah/item2.json", ""
end
it "knife list -Rfp data_bags shows only items in data_bags1" do
- knife("list --local -Rfp /data_bags").should_succeed(<<EOM, :stderr => "WARN: Child with name 'blah' found in multiple directories: #{Chef::Config.data_bag_path[0]}/blah and #{Chef::Config.data_bag_path[1]}/blah\n")
-/data_bags/bag/
-/data_bags/bag/item.json
-/data_bags/bag2/
-/data_bags/bag2/item2.json
-/data_bags/blah/
-/data_bags/blah/item1.json
+ knife("list --local -Rfp /data_bags").should_succeed(<<~EOM, stderr: "WARN: Child with name 'blah' found in multiple directories: #{Chef::Config.data_bag_path[0]}/blah and #{Chef::Config.data_bag_path[1]}/blah\n")
+ /data_bags/bag/
+ /data_bags/bag/item.json
+ /data_bags/bag2/
+ /data_bags/bag2/item2.json
+ /data_bags/blah/
+ /data_bags/blah/item1.json
EOM
end
end
@@ -459,11 +459,11 @@ EOM
file "environments2/blah.json", {}
end
it "knife show /environments/blah.json succeeds" do
- knife("show --local /environments/blah.json").should_succeed <<EOM
-/environments/blah.json:
-{
+ knife("show --local /environments/blah.json").should_succeed <<~EOM
+ /environments/blah.json:
+ {
-}
+ }
EOM
end
end
@@ -474,11 +474,11 @@ EOM
file "nodes2/blah.json", {}
end
it "knife show /nodes/blah.json succeeds" do
- knife("show --local /nodes/blah.json").should_succeed <<EOM
-/nodes/blah.json:
-{
+ knife("show --local /nodes/blah.json").should_succeed <<~EOM
+ /nodes/blah.json:
+ {
-}
+ }
EOM
end
end
@@ -489,11 +489,11 @@ EOM
file "roles2/blah.json", {}
end
it "knife show /roles/blah.json succeeds" do
- knife("show --local /roles/blah.json").should_succeed <<EOM
-/roles/blah.json:
-{
+ knife("show --local /roles/blah.json").should_succeed <<~EOM
+ /roles/blah.json:
+ {
-}
+ }
EOM
end
end
@@ -504,11 +504,11 @@ EOM
file "users2/blah.json", {}
end
it "knife show /users/blah.json succeeds" do
- knife("show --local /users/blah.json").should_succeed <<EOM
-/users/blah.json:
-{
+ knife("show --local /users/blah.json").should_succeed <<~EOM
+ /users/blah.json:
+ {
-}
+ }
EOM
end
end
@@ -523,11 +523,11 @@ EOM
context "when cwd is inside the data_bags directory" do
before { cwd "data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag2/
-bag2/item2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag2/
+ bag2/item2.json
EOM
end
end
@@ -535,32 +535,32 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client1.json
-clients/client2.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook2/
-cookbooks/cookbook2/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-data_bags/bag2/
-data_bags/bag2/item2.json
-environments/
-environments/env1.json
-environments/env2.json
-nodes/
-nodes/node1.json
-nodes/node2.json
-roles/
-roles/role1.json
-roles/role2.json
-users/
-users/user1.json
-users/user2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client1.json
+ clients/client2.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook2/
+ cookbooks/cookbook2/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ data_bags/bag2/
+ data_bags/bag2/item2.json
+ environments/
+ environments/env1.json
+ environments/env2.json
+ nodes/
+ nodes/node1.json
+ nodes/node2.json
+ roles/
+ roles/role1.json
+ roles/role2.json
+ users/
+ users/user1.json
+ users/user2.json
EOM
end
end
@@ -568,11 +568,11 @@ EOM
context "when cwd is inside data_bags2" do
before { cwd "data_bags2" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag2/
-bag2/item2.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag2/
+ bag2/item2.json
EOM
end
end
@@ -592,32 +592,32 @@ EOM
context "when cwd is at the top level" do
before { cwd "." }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client1.json
-clients/client3.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env1.json
-environments/env3.json
-nodes/
-nodes/node1.json
-nodes/node3.json
-roles/
-roles/role1.json
-roles/role3.json
-users/
-users/user1.json
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client1.json
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env1.json
+ environments/env3.json
+ nodes/
+ nodes/node1.json
+ nodes/node3.json
+ roles/
+ roles/role1.json
+ roles/role3.json
+ users/
+ users/user1.json
+ users/user3.json
EOM
end
end
@@ -625,11 +625,11 @@ EOM
context "when cwd is inside the data_bags directory" do
before { cwd "data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -637,32 +637,32 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client1.json
-clients/client3.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env1.json
-environments/env3.json
-nodes/
-nodes/node1.json
-nodes/node3.json
-roles/
-roles/role1.json
-roles/role3.json
-users/
-users/user1.json
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client1.json
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env1.json
+ environments/env3.json
+ nodes/
+ nodes/node1.json
+ nodes/node3.json
+ roles/
+ roles/role1.json
+ roles/role3.json
+ users/
+ users/user1.json
+ users/user3.json
EOM
end
end
@@ -670,11 +670,11 @@ EOM
context "when cwd is inside chef_repo2/data_bags" do
before { cwd "chef_repo2/data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -706,23 +706,23 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client3.json
-cookbooks/
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env3.json
-nodes/
-nodes/node3.json
-roles/
-roles/role3.json
-users/
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env3.json
+ nodes/
+ nodes/node3.json
+ roles/
+ roles/role3.json
+ users/
+ users/user3.json
EOM
end
end
@@ -730,9 +730,9 @@ EOM
context "when cwd is inside chef_repo2/data_bags" do
before { cwd "chef_repo2/data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -753,32 +753,32 @@ EOM
context "when cwd is at the top level" do
before { cwd "." }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client1.json
-clients/client3.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env1.json
-environments/env3.json
-nodes/
-nodes/node1.json
-nodes/node3.json
-roles/
-roles/role1.json
-roles/role3.json
-users/
-users/user1.json
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client1.json
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env1.json
+ environments/env3.json
+ nodes/
+ nodes/node1.json
+ nodes/node3.json
+ roles/
+ roles/role1.json
+ roles/role3.json
+ users/
+ users/user1.json
+ users/user3.json
EOM
end
end
@@ -786,11 +786,11 @@ EOM
context "when cwd is inside the data_bags directory" do
before { cwd "data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -798,32 +798,32 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client1.json
-clients/client3.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-data_bags/bag3/
-data_bags/bag3/item3.json
-environments/
-environments/env1.json
-environments/env3.json
-nodes/
-nodes/node1.json
-nodes/node3.json
-roles/
-roles/role1.json
-roles/role3.json
-users/
-users/user1.json
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client1.json
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ data_bags/bag3/
+ data_bags/bag3/item3.json
+ environments/
+ environments/env1.json
+ environments/env3.json
+ nodes/
+ nodes/node1.json
+ nodes/node3.json
+ roles/
+ roles/role1.json
+ roles/role3.json
+ users/
+ users/user1.json
+ users/user3.json
EOM
end
end
@@ -831,11 +831,11 @@ EOM
context "when cwd is inside chef_repo2/data_bags" do
before { cwd "chef_repo2/data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
-bag3/
-bag3/item3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
+ bag3/
+ bag3/item3.json
EOM
end
end
@@ -860,9 +860,9 @@ EOM
context "when cwd is inside the data_bags directory" do
before { cwd "data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
EOM
end
end
@@ -870,23 +870,23 @@ EOM
context "when cwd is inside chef_repo2" do
before { cwd "chef_repo2" }
it "knife list --local -Rfp lists everything" do
- knife("list --local -Rfp").should_succeed <<EOM
-clients/
-clients/client3.json
-cookbooks/
-cookbooks/cookbook3/
-cookbooks/cookbook3/metadata.rb
-data_bags/
-data_bags/bag/
-data_bags/bag/item.json
-environments/
-environments/env3.json
-nodes/
-nodes/node3.json
-roles/
-roles/role3.json
-users/
-users/user3.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ clients/
+ clients/client3.json
+ cookbooks/
+ cookbooks/cookbook3/
+ cookbooks/cookbook3/metadata.rb
+ data_bags/
+ data_bags/bag/
+ data_bags/bag/item.json
+ environments/
+ environments/env3.json
+ nodes/
+ nodes/node3.json
+ roles/
+ roles/role3.json
+ users/
+ users/user3.json
EOM
end
end
@@ -911,26 +911,26 @@ EOM
end
it "knife list --local -Rfp / lists data bags" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/data_bags/
-/data_bags/bag/
-/data_bags/bag/item.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /data_bags/
+ /data_bags/bag/
+ /data_bags/bag/item.json
EOM
end
it "knife list --local -Rfp /data_bags lists data bags" do
- knife("list --local -Rfp /data_bags").should_succeed <<EOM
-/data_bags/bag/
-/data_bags/bag/item.json
+ knife("list --local -Rfp /data_bags").should_succeed <<~EOM
+ /data_bags/bag/
+ /data_bags/bag/item.json
EOM
end
context "when cwd is inside the data_bags directory" do
before { cwd "data_bags" }
it "knife list --local -Rfp lists data bags" do
- knife("list --local -Rfp").should_succeed <<EOM
-bag/
-bag/item.json
+ knife("list --local -Rfp").should_succeed <<~EOM
+ bag/
+ bag/item.json
EOM
end
end
diff --git a/spec/integration/knife/chef_repository_file_system_spec.rb b/spec/integration/knife/chef_repository_file_system_spec.rb
index 222d3aee8a..538d6c5a63 100644
--- a/spec/integration/knife/chef_repository_file_system_spec.rb
+++ b/spec/integration/knife/chef_repository_file_system_spec.rb
@@ -32,11 +32,11 @@ describe "General chef_repo file system checks", :workstation do
end
it "knife list --local -Rfp / returns them" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/data_bags/
-/data_bags/bag1/
-/environments/
-/roles/
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /data_bags/
+ /data_bags/bag1/
+ /environments/
+ /roles/
EOM
end
end
@@ -53,8 +53,8 @@ EOM
before { directory "cookbooks/cookbook1" }
it "knife list --local -Rfp / does not return it" do
- knife("list --local -Rfp /").should_succeed(<<EOM, :stderr => "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
-/cookbooks/
+ knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
+ /cookbooks/
EOM
end
end
@@ -63,8 +63,8 @@ EOM
before { directory "cookbooks/cookbook1/recipes" }
it "knife list --local -Rfp / does not return it" do
- knife("list --local -Rfp /").should_succeed(<<EOM, :stderr => "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
-/cookbooks/
+ knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
+ /cookbooks/
EOM
end
end
@@ -76,12 +76,12 @@ EOM
end
it "knife list --local -Rfp / does not return the empty ones" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/templates/
-/cookbooks/cookbook1/templates/default/
-/cookbooks/cookbook1/templates/default/x.txt
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/templates/
+ /cookbooks/cookbook1/templates/default/
+ /cookbooks/cookbook1/templates/default/x.txt
EOM
end
end
@@ -90,8 +90,8 @@ EOM
before { directory "cookbooks/cookbook1/templates/default" }
it "knife list --local -Rfp / does not return it" do
- knife("list --local -Rfp /").should_succeed(<<EOM, :stderr => "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
-/cookbooks/
+ knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
+ /cookbooks/
EOM
end
end
@@ -104,12 +104,12 @@ EOM
end
it "knife list --local -Rfp / does not return the empty ones" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/templates/
-/cookbooks/cookbook1/templates/default/
-/cookbooks/cookbook1/templates/default/x.txt
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/templates/
+ /cookbooks/cookbook1/templates/default/
+ /cookbooks/cookbook1/templates/default/x.txt
EOM
end
end
@@ -146,14 +146,14 @@ EOM
end
it "knife list --local -Rfp / should NOT return them" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/environments/
-/environments/environment1.json
-/roles/
-/roles/role1.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /environments/
+ /environments/environment1.json
+ /roles/
+ /roles/role1.json
EOM
end
end
@@ -161,8 +161,8 @@ EOM
when_the_repository "has a file in cookbooks/" do
before { file "cookbooks/file", "" }
it "does not show up in list -Rfp" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
EOM
end
end
@@ -170,8 +170,8 @@ EOM
when_the_repository "has a file in data_bags/" do
before { file "data_bags/file", "" }
it "does not show up in list -Rfp" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/data_bags/
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /data_bags/
EOM
end
end
diff --git a/spec/integration/knife/chefignore_spec.rb b/spec/integration/knife/chefignore_spec.rb
index aa5a3979cc..eb36f4675f 100644
--- a/spec/integration/knife/chefignore_spec.rb
+++ b/spec/integration/knife/chefignore_spec.rb
@@ -45,17 +45,17 @@ describe "chefignore tests", :workstation do
it "matching files and directories get ignored" do
# NOTE: many of the "chefignore" files should probably not show up
# themselves, but we have other tests that talk about that
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/chefignore
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/x.json
-/environments/
-/environments/x.json
-/roles/
-/roles/x.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/chefignore
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/x.json
+ /environments/
+ /environments/x.json
+ /roles/
+ /roles/x.json
EOM
end
end
@@ -69,8 +69,8 @@ EOM
end
it "the cookbook is not listed" do
- knife("list --local -Rfp /").should_succeed(<<EOM, :stderr => "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
-/cookbooks/
+ knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Cookbook 'cookbook1' is empty or entirely chefignored at #{Chef::Config.chef_repo_path}/cookbooks/cookbook1\n")
+ /cookbooks/
EOM
end
end
@@ -87,12 +87,12 @@ EOM
before { file "cookbooks/chefignore", "x.json\n" }
it "matching files and directories get ignored in all cookbooks" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -104,12 +104,12 @@ EOM
end
it "matching files and directories get ignored in all cookbooks" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -122,16 +122,16 @@ EOM
end
it "matching directories get ignored" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/x.json
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/recipes/
-/cookbooks/cookbook2/recipes/y.rb
-/cookbooks/cookbook2/x.json
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/x.json
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/recipes/
+ /cookbooks/cookbook2/recipes/y.rb
+ /cookbooks/cookbook2/x.json
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -143,16 +143,16 @@ EOM
end
it "matching directories do NOT get ignored" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/recipes/
-/cookbooks/cookbook1/recipes/y.rb
-/cookbooks/cookbook1/x.json
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/x.json
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/recipes/
+ /cookbooks/cookbook1/recipes/y.rb
+ /cookbooks/cookbook1/x.json
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/x.json
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -165,14 +165,14 @@ EOM
end
it "ignores the subdirectory entirely" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/x.json
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/x.json
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/x.json
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/x.json
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -183,14 +183,14 @@ EOM
end
it "nothing is ignored" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/x.json
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/x.json
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/x.json
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/x.json
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -201,12 +201,12 @@ EOM
end
it "matching files and directories get ignored in all cookbooks" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/y.json
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/y.json
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/y.json
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/y.json
EOM
end
end
@@ -233,12 +233,12 @@ EOM
file "cookbooks2/chefignore", "x.json\n"
end
it "chefignores apply only to the directories they are in" do
- knife("list --local -Rfp /").should_succeed <<EOM
-/cookbooks/
-/cookbooks/mycookbook/
-/cookbooks/mycookbook/x.json
-/cookbooks/yourcookbook/
-/cookbooks/yourcookbook/metadata.rb
+ knife("list --local -Rfp /").should_succeed <<~EOM
+ /cookbooks/
+ /cookbooks/mycookbook/
+ /cookbooks/mycookbook/x.json
+ /cookbooks/yourcookbook/
+ /cookbooks/yourcookbook/metadata.rb
EOM
end
@@ -251,13 +251,13 @@ EOM
end
it "chefignores apply only to the winning cookbook" do
- knife("list --local -Rfp /").should_succeed(<<EOM, :stderr => "WARN: Child with name 'yourcookbook' found in multiple directories: #{Chef::Config.chef_repo_path}/cookbooks1/yourcookbook and #{Chef::Config.chef_repo_path}/cookbooks2/yourcookbook\n")
-/cookbooks/
-/cookbooks/mycookbook/
-/cookbooks/mycookbook/x.json
-/cookbooks/yourcookbook/
-/cookbooks/yourcookbook/onlyincookbooks1.rb
-/cookbooks/yourcookbook/x.json
+ knife("list --local -Rfp /").should_succeed(<<~EOM, stderr: "WARN: Child with name 'yourcookbook' found in multiple directories: #{Chef::Config.chef_repo_path}/cookbooks1/yourcookbook and #{Chef::Config.chef_repo_path}/cookbooks2/yourcookbook\n")
+ /cookbooks/
+ /cookbooks/mycookbook/
+ /cookbooks/mycookbook/x.json
+ /cookbooks/yourcookbook/
+ /cookbooks/yourcookbook/onlyincookbooks1.rb
+ /cookbooks/yourcookbook/x.json
EOM
end
end
@@ -269,9 +269,9 @@ EOM
file "cookbooks/chefignore/metadata.rb", {}
end
it "knife list -Rfp /cookbooks shows it" do
- knife("list --local -Rfp /cookbooks").should_succeed <<EOM
-/cookbooks/chefignore/
-/cookbooks/chefignore/metadata.rb
+ knife("list --local -Rfp /cookbooks").should_succeed <<~EOM
+ /cookbooks/chefignore/
+ /cookbooks/chefignore/metadata.rb
EOM
end
end
@@ -289,11 +289,11 @@ EOM
]
end
it "knife list -Rfp /cookbooks shows the chefignore cookbook" do
- knife("list --local -Rfp /cookbooks").should_succeed <<EOM
-/cookbooks/blah/
-/cookbooks/blah/metadata.rb
-/cookbooks/chefignore/
-/cookbooks/chefignore/metadata.rb
+ knife("list --local -Rfp /cookbooks").should_succeed <<~EOM
+ /cookbooks/blah/
+ /cookbooks/blah/metadata.rb
+ /cookbooks/chefignore/
+ /cookbooks/chefignore/metadata.rb
EOM
end
end
diff --git a/spec/integration/knife/client_bulk_delete_spec.rb b/spec/integration/knife/client_bulk_delete_spec.rb
index a422401af6..42bfe0396a 100644
--- a/spec/integration/knife/client_bulk_delete_spec.rb
+++ b/spec/integration/knife/client_bulk_delete_spec.rb
@@ -33,40 +33,40 @@ describe "knife client bulk delete", :workstation do
end
it "deletes all matching clients" do
- knife("client bulk delete ^ca.*", input: "Y").should_succeed <<EOM
-The following clients will be deleted:
+ knife("client bulk delete ^ca.*", input: "Y").should_succeed <<~EOM
+ The following clients will be deleted:
-car cat
+ car cat
-Are you sure you want to delete these clients? (Y/N) Deleted client car
-Deleted client cat
+ Are you sure you want to delete these clients? (Y/N) Deleted client car
+ Deleted client cat
EOM
- knife("client list").should_succeed <<EOM
-cdr
-chef-validator
-chef-webui
-concat
-cons
+ knife("client list").should_succeed <<~EOM
+ cdr
+ chef-validator
+ chef-webui
+ concat
+ cons
EOM
end
it "deletes all matching clients when unanchored" do
- knife("client bulk delete ca.*", input: "Y").should_succeed <<EOM
-The following clients will be deleted:
+ knife("client bulk delete ca.*", input: "Y").should_succeed <<~EOM
+ The following clients will be deleted:
-car cat concat
+ car cat concat
-Are you sure you want to delete these clients? (Y/N) Deleted client car
-Deleted client cat
-Deleted client concat
+ Are you sure you want to delete these clients? (Y/N) Deleted client car
+ Deleted client cat
+ Deleted client concat
EOM
- knife("client list").should_succeed <<EOM
-cdr
-chef-validator
-chef-webui
-cons
+ knife("client list").should_succeed <<~EOM
+ cdr
+ chef-validator
+ chef-webui
+ cons
EOM
end
end
@@ -81,49 +81,49 @@ EOM
end
it "refuses to delete a validator normally" do
- knife("client bulk delete ^ca.*", input: "Y").should_succeed <<EOM
-The following clients are validators and will not be deleted:
+ knife("client bulk delete ^ca.*", input: "Y").should_succeed <<~EOM
+ The following clients are validators and will not be deleted:
-car-validator
+ car-validator
-You must specify --delete-validators to delete the validator clients
-The following clients will be deleted:
+ You must specify --delete-validators to delete the validator clients
+ The following clients will be deleted:
-car cat
+ car cat
-Are you sure you want to delete these clients? (Y/N) Deleted client car
-Deleted client cat
+ Are you sure you want to delete these clients? (Y/N) Deleted client car
+ Deleted client cat
EOM
- knife("client list").should_succeed <<EOM
-car-validator
-cdr
-chef-validator
-chef-webui
-cons
+ knife("client list").should_succeed <<~EOM
+ car-validator
+ cdr
+ chef-validator
+ chef-webui
+ cons
EOM
end
it "deletes a validator when told to" do
- knife("client bulk delete ^ca.* -D", input: "Y\nY").should_succeed <<EOM
-The following validators will be deleted:
+ knife("client bulk delete ^ca.* -D", input: "Y\nY").should_succeed <<~EOM
+ The following validators will be deleted:
-car-validator
+ car-validator
-Are you sure you want to delete these validators? (Y/N) Deleted client car-validator
-The following clients will be deleted:
+ Are you sure you want to delete these validators? (Y/N) Deleted client car-validator
+ The following clients will be deleted:
-car cat
+ car cat
-Are you sure you want to delete these clients? (Y/N) Deleted client car
-Deleted client cat
+ Are you sure you want to delete these clients? (Y/N) Deleted client car
+ Deleted client cat
EOM
- knife("client list").should_succeed <<EOM
-cdr
-chef-validator
-chef-webui
-cons
+ knife("client list").should_succeed <<~EOM
+ cdr
+ chef-validator
+ chef-webui
+ cons
EOM
end
end
diff --git a/spec/integration/knife/client_create_spec.rb b/spec/integration/knife/client_create_spec.rb
index 10172833c8..d24755a48a 100644
--- a/spec/integration/knife/client_create_spec.rb
+++ b/spec/integration/knife/client_create_spec.rb
@@ -33,11 +33,11 @@ describe "knife client create", :workstation do
it "creates a new validator client" do
knife("client create -k --validator bah").should_succeed stderr: out
- knife("client show bah").should_succeed <<EOM
-admin: false
-chef_type: client
-name: bah
-validator: true
+ knife("client show bah").should_succeed <<~EOM
+ admin: false
+ chef_type: client
+ name: bah
+ validator: true
EOM
end
diff --git a/spec/integration/knife/client_delete_spec.rb b/spec/integration/knife/client_delete_spec.rb
index d135dd0a5b..914827cb46 100644
--- a/spec/integration/knife/client_delete_spec.rb
+++ b/spec/integration/knife/client_delete_spec.rb
@@ -33,29 +33,29 @@ describe "knife client delete", :workstation do
end
it "deletes a client" do
- knife("client delete car", input: "Y").should_succeed <<EOM
-Do you really want to delete car? (Y/N) Deleted client[car]
+ knife("client delete car", input: "Y").should_succeed <<~EOM
+ Do you really want to delete car? (Y/N) Deleted client[car]
EOM
- knife("client list").should_succeed <<EOM
-car-validator
-cat
-cdr
-chef-validator
-chef-webui
-cons
+ knife("client list").should_succeed <<~EOM
+ car-validator
+ cat
+ cdr
+ chef-validator
+ chef-webui
+ cons
EOM
end
it "refuses to delete a validator normally" do
- knife("client delete car-validator", input: "Y").should_fail exit_code: 2, stdout: "Do you really want to delete car-validator? (Y/N) ", stderr: <<EOM
-FATAL: You must specify --delete-validators to delete the validator client car-validator
+ knife("client delete car-validator", input: "Y").should_fail exit_code: 2, stdout: "Do you really want to delete car-validator? (Y/N) ", stderr: <<~EOM
+ FATAL: You must specify --delete-validators to delete the validator client car-validator
EOM
end
it "deletes a validator correctly" do
- knife("client delete car-validator -D", input: "Y").should_succeed <<EOM
-Do you really want to delete car-validator? (Y/N) Deleted client[car-validator]
+ knife("client delete car-validator -D", input: "Y").should_succeed <<~EOM
+ Do you really want to delete car-validator? (Y/N) Deleted client[car-validator]
EOM
end
diff --git a/spec/integration/knife/client_key_delete_spec.rb b/spec/integration/knife/client_key_delete_spec.rb
index d5827aa545..061a3fea76 100644
--- a/spec/integration/knife/client_key_delete_spec.rb
+++ b/spec/integration/knife/client_key_delete_spec.rb
@@ -31,8 +31,8 @@ describe "knife client key delete", :workstation do
it "deletes a client" do
out = "Do you really want to delete the key named new for the client named car? (Y/N) "
knife("client key create -k new car")
- knife("client key delete car new", input: "Y").should_succeed stdout: out, stderr: <<EOM
-Deleted key named new for the client named car
+ knife("client key delete car new", input: "Y").should_succeed stdout: out, stderr: <<~EOM
+ Deleted key named new for the client named car
EOM
knife("client key list car").should_succeed ""
diff --git a/spec/integration/knife/client_key_list_spec.rb b/spec/integration/knife/client_key_list_spec.rb
index de9894622e..0969d5fb98 100644
--- a/spec/integration/knife/client_key_list_spec.rb
+++ b/spec/integration/knife/client_key_list_spec.rb
@@ -41,10 +41,10 @@ describe "knife client key list", :workstation do
end
it "shows detailed output" do
- knife("client key list -w cons").should_succeed <<EOM
-expired: http://127.0.0.1:8900/clients/cons/keys/expired (expired)
-new: http://127.0.0.1:8900/clients/cons/keys/new
-next_month: http://127.0.0.1:8900/clients/cons/keys/next_month
+ knife("client key list -w cons").should_succeed <<~EOM
+ expired: http://127.0.0.1:8900/clients/cons/keys/expired (expired)
+ new: http://127.0.0.1:8900/clients/cons/keys/new
+ next_month: http://127.0.0.1:8900/clients/cons/keys/next_month
EOM
end
diff --git a/spec/integration/knife/client_list_spec.rb b/spec/integration/knife/client_list_spec.rb
index 4159df73f1..41cf8dcbb6 100644
--- a/spec/integration/knife/client_list_spec.rb
+++ b/spec/integration/knife/client_list_spec.rb
@@ -33,14 +33,14 @@ describe "knife client list", :workstation do
end
it "lists the clients" do
- knife("client list").should_succeed <<EOM
-car
-car-validator
-cat
-cdr
-chef-validator
-chef-webui
-cons
+ knife("client list").should_succeed <<~EOM
+ car
+ car-validator
+ cat
+ cdr
+ chef-validator
+ chef-webui
+ cons
EOM
end
diff --git a/spec/integration/knife/common_options_spec.rb b/spec/integration/knife/common_options_spec.rb
index 6b6b83aafe..e0622eb801 100644
--- a/spec/integration/knife/common_options_spec.rb
+++ b/spec/integration/knife/common_options_spec.rb
@@ -28,7 +28,7 @@ describe "knife common options", :workstation do
Chef::Config.treat_deprecation_warnings_as_errors(false)
end
- let(:local_listen_warning) { /\Awarn:.*local.*listen.*$/i }
+ let(:local_listen_warning) { /\Awarn:.*local.*listen.*$/im }
when_the_repository "has a node" do
before { file "nodes/x.json", {} }
@@ -67,34 +67,34 @@ describe "knife common options", :workstation do
context "and there is a private key" do
before do
- file "mykey.pem", <<EOM
------BEGIN RSA PRIVATE KEY-----
-MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
-0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
-NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
-0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
-AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
-HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
-8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
-zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
-k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
-i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
-G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
-ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
-awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
-7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
-g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
-Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
-HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
-V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
-fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
-lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
-c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
-fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
-YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
-syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
-+vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
------END RSA PRIVATE KEY-----
+ file "mykey.pem", <<~EOM
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
+ 0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
+ NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
+ 0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
+ AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
+ HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
+ 8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
+ zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
+ k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
+ i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
+ G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
+ ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
+ awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
+ 7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
+ g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
+ Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
+ HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
+ V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
+ fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
+ lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
+ c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
+ fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
+ YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
+ syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
+ +vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
+ -----END RSA PRIVATE KEY-----
EOM
end
@@ -125,7 +125,7 @@ EOM
context "when the default port (8889) is already bound" do
before :each do
begin
- @server = ChefZero::Server.new(:host => "localhost", :port => 8889)
+ @server = ChefZero::Server.new(host: "localhost", port: 8889)
@server.start_background
rescue Errno::EADDRINUSE
# OK. Don't care who has it in use, as long as *someone* does.
@@ -144,7 +144,7 @@ EOM
context "when port 9999 is already bound" do
before :each do
begin
- @server = ChefZero::Server.new(:host => "localhost", :port => 9999)
+ @server = ChefZero::Server.new(host: "localhost", port: 9999)
@server.start_background
rescue Errno::EADDRINUSE
# OK. Don't care who has it in use, as long as *someone* does.
diff --git a/spec/integration/knife/config_get_profile_spec.rb b/spec/integration/knife/config_get_profile_spec.rb
new file mode 100644
index 0000000000..e97b24b869
--- /dev/null
+++ b/spec/integration/knife/config_get_profile_spec.rb
@@ -0,0 +1,112 @@
+#
+# Copyright 2018, Noah Kantrowitz
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+require "support/shared/integration/integration_helper"
+require "support/shared/context/config"
+
+describe "knife config get-profile", :workstation do
+ include IntegrationSupport
+ include KnifeSupport
+
+ include_context "default config options"
+ include_context "with a chef repo"
+
+ let(:cmd_args) { [] }
+
+ subject do
+ cmd = knife("config", "get-profile", *cmd_args, instance_filter: lambda { |instance|
+ # Fake the failsafe check because this command doesn't actually process knife.rb.
+ $__KNIFE_INTEGRATION_FAILSAFE_CHECK << " ole"
+ })
+ cmd.stdout
+ end
+
+ around do |ex|
+ # Store and reset the value of some env vars.
+ old_chef_home = ENV["CHEF_HOME"]
+ old_knife_home = ENV["KNIFE_HOME"]
+ old_home = ENV["HOME"]
+ old_wd = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME"
+ # Clear these out because they are cached permanently.
+ ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) }
+ Chef::Knife::ConfigGetProfile.reset_config_loader!
+ begin
+ ex.run
+ ensure
+ ENV["CHEF_HOME"] = old_chef_home
+ ENV["KNIFE_HOME"] = old_knife_home
+ ENV["HOME"] = old_home
+ Dir.chdir(old_wd)
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = nil
+ end
+ end
+
+ before do
+ # Always run from the temp folder. This can't be in the `around` block above
+ # because it has to run after the before set in the "with a chef repo" shared context.
+ directory("repo")
+ Dir.chdir(path_to("repo"))
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ENV["HOME"] = path_to(".")
+ end
+
+ context "with no configuration" do
+ it { is_expected.to eq "default\n" }
+ end
+
+ context "with --profile" do
+ let(:cmd_args) { %w{--profile production} }
+ it { is_expected.to eq "production\n" }
+ end
+
+ context "with an environment variable" do
+ around do |ex|
+ old_chef_profile = ENV["CHEF_PROFILE"]
+ begin
+ ENV["CHEF_PROFILE"] = "staging"
+ ex.run
+ ensure
+ ENV["CHEF_PROFILE"] = old_chef_profile
+ end
+ end
+
+ it { is_expected.to eq "staging\n" }
+ end
+
+ context "with a context file" do
+ before { file(".chef/context", "development\n") }
+ it { is_expected.to eq "development\n" }
+ end
+
+ context "with a context file under $CHEF_HOME" do
+ before do
+ file("chefhome/.chef/context", "other\n")
+ ENV["CHEF_HOME"] = path_to("chefhome")
+ end
+
+ it { is_expected.to eq "other\n" }
+ end
+
+ context "with a context file under $KNIFE_HOME" do
+ before do
+ file("knifehome/.chef/context", "other\n")
+ ENV["KNIFE_HOME"] = path_to("knifehome")
+ end
+
+ it { is_expected.to eq "other\n" }
+ end
+end
diff --git a/spec/integration/knife/config_get_spec.rb b/spec/integration/knife/config_get_spec.rb
new file mode 100644
index 0000000000..f34d096051
--- /dev/null
+++ b/spec/integration/knife/config_get_spec.rb
@@ -0,0 +1,183 @@
+#
+# Copyright 2018, Noah Kantrowitz
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+require "support/shared/integration/integration_helper"
+require "support/shared/context/config"
+
+describe "knife config get", :workstation do
+ include IntegrationSupport
+ include KnifeSupport
+
+ include_context "default config options"
+ include_context "with a chef repo"
+
+ let(:cmd_args) { [] }
+
+ subject do
+ cmd = knife("config", "get", *cmd_args, instance_filter: lambda { |instance|
+ # Clear the stub set up in KnifeSupport.
+ allow(File).to receive(:file?).and_call_original
+ # Lies, damn lies, and config files. We need to allow normal config loading
+ # behavior to be able to test stuff.
+ instance.config.delete(:config_file)
+ $__KNIFE_INTEGRATION_FAILSAFE_CHECK << " ole"
+ })
+ cmd.stdout
+ end
+
+ around do |ex|
+ # Store and reset the value of some env vars.
+ old_chef_home = ENV["CHEF_HOME"]
+ old_knife_home = ENV["KNIFE_HOME"]
+ old_home = ENV["HOME"]
+ old_wd = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME"
+ # Clear these out because they are cached permanently.
+ ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) }
+ Chef::Knife::ConfigGet.reset_config_loader!
+ begin
+ ex.run
+ ensure
+ ENV["CHEF_HOME"] = old_chef_home
+ ENV["KNIFE_HOME"] = old_knife_home
+ ENV["HOME"] = old_home
+ Dir.chdir(old_wd)
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = nil
+ end
+ end
+
+ before do
+ # Always run from the temp folder. This can't be in the `around` block above
+ # because it has to run after the before set in the "with a chef repo" shared context.
+ directory("repo")
+ Dir.chdir(path_to("repo"))
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ENV["HOME"] = path_to(".")
+ end
+
+ context "with a global knife.rb" do
+ before { file(".chef/knife.rb", "node_name 'one'\n") }
+
+ it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/.chef/knife.rb$}) }
+ it { is_expected.to match(/^node_name:\s+one$/) }
+ end
+
+ context "with a repo knife.rb" do
+ before { file("repo/.chef/knife.rb", "node_name 'two'\n") }
+
+ it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/repo/.chef/knife.rb$}) }
+ it { is_expected.to match(/^node_name:\s+two$/) }
+ end
+
+ context "with both knife.rb" do
+ before do
+ file(".chef/knife.rb", "node_name 'one'\n")
+ file("repo/.chef/knife.rb", "node_name 'two'\n")
+ end
+
+ it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/repo/.chef/knife.rb$}) }
+ it { is_expected.to match(/^node_name:\s+two$/) }
+ end
+
+ context "with a credentials file" do
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { is_expected.to match(%r{^Loading from credentials file .*/#{File.basename(path_to("."))}/.chef/credentials$}) }
+ it { is_expected.to match(/^node_name:\s+three$/) }
+ end
+
+ context "with a credentials file and knife.rb" do
+ before do
+ file(".chef/knife.rb", "node_name 'one'\n")
+ file(".chef/credentials", "[default]\nclient_name = \"three\"\n")
+ end
+
+ it { is_expected.to match(%r{^Loading from configuration file .*/#{File.basename(path_to("."))}/.chef/knife.rb$}) }
+ it { is_expected.to match(%r{^Loading from credentials file .*/#{File.basename(path_to("."))}/.chef/credentials$}) }
+ it { is_expected.to match(/^node_name:\s+one$/) }
+ end
+
+ context "with a credentials file and CHEF_HOME" do
+ before do
+ file(".chef/credentials", "[default]\nclient_name = \"three\"\n")
+ file("foo/.chef/credentials", "[default]\nclient_name = \"four\"\n")
+ ENV["CHEF_HOME"] = path_to("foo")
+ end
+
+ it { is_expected.to match(%r{^Loading from credentials file .*/#{File.basename(path_to("."))}/foo/.chef/credentials$}) }
+ it { is_expected.to match(/^node_name:\s+four$/) }
+ end
+
+ context "with a credentials file and KNIFE_HOME" do
+ before do
+ file(".chef/credentials", "[default]\nclient_name = \"three\"\n")
+ file("bar/.chef/credentials", "[default]\nclient_name = \"four\"\n")
+ ENV["KNIFE_HOME"] = path_to("bar")
+ end
+
+ it { is_expected.to match(%r{^Loading from credentials file .*/#{File.basename(path_to("."))}/bar/.chef/credentials$}) }
+ it { is_expected.to match(/^node_name:\s+four$/) }
+ end
+
+ context "with single argument" do
+ let(:cmd_args) { %w{node_name} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { is_expected.to match(/^node_name:\s+three\Z/) }
+ end
+
+ context "with two arguments" do
+ let(:cmd_args) { %w{node_name client_key} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\nclient_key = \"three.pem\"") }
+
+ it { is_expected.to match(/^client_key:\s+\S*\/.chef\/three.pem\nnode_name:\s+three\Z/) }
+ end
+
+ context "with a dotted argument" do
+ let(:cmd_args) { %w{knife.ssh_user} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n[default.knife]\nssh_user = \"foo\"\n") }
+
+ it { is_expected.to match(/^knife.ssh_user:\s+foo\Z/) }
+ end
+
+ context "with regex argument" do
+ let(:cmd_args) { %w{/name/} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { is_expected.to match(/^node_name:\s+three\Z/) }
+ end
+
+ context "with --all" do
+ let(:cmd_args) { %w{-a /key_contents/} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { is_expected.to match(/^client_key_contents:\s+\nvalidation_key_contents:\s+\Z/) }
+ end
+
+ context "with --raw" do
+ let(:cmd_args) { %w{-r node_name} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { is_expected.to eq("three\n") }
+ end
+
+ context "with --format=json" do
+ let(:cmd_args) { %w{--format=json node_name} }
+ before { file(".chef/credentials", "[default]\nclient_name = \"three\"\n") }
+
+ it { expect(JSON.parse(subject)).to eq({ "node_name" => "three" }) }
+ end
+end
diff --git a/spec/integration/knife/config_list_profiles_spec.rb b/spec/integration/knife/config_list_profiles_spec.rb
new file mode 100644
index 0000000000..32846f9999
--- /dev/null
+++ b/spec/integration/knife/config_list_profiles_spec.rb
@@ -0,0 +1,188 @@
+#
+# Copyright 2018, Noah Kantrowitz
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+require "support/shared/integration/integration_helper"
+require "support/shared/context/config"
+
+describe "knife config list-profiles", :workstation do
+ include IntegrationSupport
+ include KnifeSupport
+
+ include_context "default config options"
+ include_context "with a chef repo"
+
+ let(:cmd_args) { [] }
+ let(:knife_list_profiles) do
+ knife("config", "list-profiles", *cmd_args, instance_filter: proc {
+ # Clear the stub set up in KnifeSupport.
+ allow(File).to receive(:file?).and_call_original
+ })
+ end
+ subject { knife_list_profiles.stdout }
+
+ around do |ex|
+ # Store and reset the value of some env vars.
+ old_home = ENV["HOME"]
+ old_wd = Dir.pwd
+ # Clear these out because they are cached permanently.
+ ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) }
+ Chef::Knife::ConfigListProfiles.reset_config_loader!
+ begin
+ ex.run
+ ensure
+ ENV["HOME"] = old_home
+ Dir.chdir(old_wd)
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ end
+ end
+
+ before do
+ # Always run from the temp folder. This can't be in the `around` block above
+ # because it has to run after the before set in the "with a chef repo" shared context.
+ directory("repo")
+ Dir.chdir(path_to("repo"))
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ENV["HOME"] = path_to(".")
+ end
+
+ # NOTE: The funky formatting with # at the end of the line of some of the
+ # output examples are because of how the format strings are built, there is
+ # substantial trailing whitespace in most cases which many editors "helpfully" remove.
+
+ context "with no credentials file" do
+ subject { knife_list_profiles.stderr }
+ it { is_expected.to eq "FATAL: No profiles found, #{path_to(".chef/credentials")} does not exist or is empty\n" }
+ end
+
+ context "with an empty credentials file" do
+ before { file(".chef/credentials", "") }
+ subject { knife_list_profiles.stderr }
+ it { is_expected.to eq "FATAL: No profiles found, #{path_to(".chef/credentials")} does not exist or is empty\n" }
+ end
+
+ context "with a simple default profile" do
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it { is_expected.to eq <<~EOH.delete("#") }
+ Profile Client Key Server #
+ ----------------------------------------------------------------------------------#
+ *default testuser ~/.chef/testkey.pem https://example.com/organizations/testorg#
+ EOH
+ end
+
+ context "with multiple profiles" do
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+
+ [prod]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/prod"
+
+ [qa]
+ client_name = "qauser"
+ client_key = "~/src/qauser.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it { is_expected.to eq <<~EOH.delete("#") }
+ Profile Client Key Server #
+ ----------------------------------------------------------------------------------#
+ *default testuser ~/.chef/testkey.pem https://example.com/organizations/testorg#
+ prod testuser ~/.chef/testkey.pem https://example.com/organizations/prod #
+ qa qauser ~/src/qauser.pem https://example.com/organizations/testorg#
+ EOH
+ end
+
+ context "with a non-default active profile" do
+ let(:cmd_args) { %w{--profile prod} }
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+
+ [prod]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/prod"
+
+ [qa]
+ client_name = "qauser"
+ client_key = "~/src/qauser.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it { is_expected.to eq <<~EOH.delete("#") }
+ Profile Client Key Server #
+ ----------------------------------------------------------------------------------#
+ default testuser ~/.chef/testkey.pem https://example.com/organizations/testorg#
+ *prod testuser ~/.chef/testkey.pem https://example.com/organizations/prod #
+ qa qauser ~/src/qauser.pem https://example.com/organizations/testorg#
+ EOH
+ end
+
+ context "with a minimal profile" do
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it { is_expected.to match %r{^*default .*? https://example.com/organizations/testorg$} }
+ end
+
+ context "with -i" do
+ let(:cmd_args) { %w{-i} }
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it { is_expected.to eq <<~EOH.delete("#") }
+ Profile Client Key Server #
+ ----------------------------------------------------------------#
+ *default https://example.com/organizations/testorg#
+ EOH
+ end
+
+ context "with --format=json" do
+ let(:cmd_args) { %w{--format=json node_name} }
+ before { file(".chef/credentials", <<~EOH) }
+ [default]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+
+ [prod]
+ client_name = "testuser"
+ client_key = "testkey.pem"
+ chef_server_url = "https://example.com/organizations/prod"
+
+ [qa]
+ client_name = "qauser"
+ client_key = "~/src/qauser.pem"
+ chef_server_url = "https://example.com/organizations/testorg"
+ EOH
+ it {
+ expect(JSON.parse(subject)).to eq [
+ { "profile" => "default", "active" => true, "client_name" => "testuser", "client_key" => path_to(".chef/testkey.pem"), "server_url" => "https://example.com/organizations/testorg" },
+ { "profile" => "prod", "active" => false, "client_name" => "testuser", "client_key" => path_to(".chef/testkey.pem"), "server_url" => "https://example.com/organizations/prod" },
+ { "profile" => "qa", "active" => false, "client_name" => "qauser", "client_key" => path_to("src/qauser.pem"), "server_url" => "https://example.com/organizations/testorg" },
+ ] }
+ end
+end
diff --git a/spec/integration/knife/config_use_profile_spec.rb b/spec/integration/knife/config_use_profile_spec.rb
new file mode 100644
index 0000000000..a021dbbe6f
--- /dev/null
+++ b/spec/integration/knife/config_use_profile_spec.rb
@@ -0,0 +1,100 @@
+#
+# Copyright 2018, Noah Kantrowitz
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+require "support/shared/integration/integration_helper"
+require "support/shared/context/config"
+
+describe "knife config use-profile", :workstation do
+ include IntegrationSupport
+ include KnifeSupport
+
+ include_context "default config options"
+ include_context "with a chef repo"
+
+ let(:cmd_args) { [] }
+
+ let(:knife_use_profile) do
+ knife("config", "use-profile", *cmd_args, instance_filter: lambda { |instance|
+ # Fake the failsafe check because this command doesn't actually process knife.rb.
+ $__KNIFE_INTEGRATION_FAILSAFE_CHECK << " ole"
+ })
+ end
+
+ subject { knife_use_profile.stdout }
+
+ around do |ex|
+ # Store and reset the value of some env vars.
+ old_chef_home = ENV["CHEF_HOME"]
+ old_knife_home = ENV["KNIFE_HOME"]
+ old_home = ENV["HOME"]
+ old_wd = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = "KNIFE_HOME"
+ # Clear these out because they are cached permanently.
+ ChefConfig::PathHelper.class_exec { remove_class_variable(:@@home_dir) }
+ Chef::Knife::ConfigUseProfile.reset_config_loader!
+ begin
+ ex.run
+ ensure
+ ENV["CHEF_HOME"] = old_chef_home
+ ENV["KNIFE_HOME"] = old_knife_home
+ ENV["HOME"] = old_home
+ Dir.chdir(old_wd)
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ChefConfig::PathHelper.per_tool_home_environment = nil
+ end
+ end
+
+ before do
+ # Always run from the temp folder. This can't be in the `around` block above
+ # because it has to run after the before set in the "with a chef repo" shared context.
+ directory("repo")
+ Dir.chdir(path_to("repo"))
+ ENV[ChefConfig.windows? ? "CD" : "PWD"] = Dir.pwd
+ ENV["HOME"] = path_to(".")
+ end
+
+ context "with no argument" do
+ subject { knife_use_profile.stderr }
+ it { is_expected.to eq "FATAL: You must specify a profile\n" }
+ end
+
+ context "with an argument" do
+ let(:cmd_args) { %w{production} }
+ it do
+ is_expected.to eq "Set default profile to production\n"
+ expect(File.read(path_to(".chef/context"))).to eq "production\n"
+ end
+ end
+
+ context "with $CHEF_HOME" do
+ let(:cmd_args) { %w{staging} }
+ before { ENV["CHEF_HOME"] = path_to("chefhome"); file("chefhome/tmp", "") }
+ it do
+ is_expected.to eq "Set default profile to staging\n"
+ expect(File.read(path_to("chefhome/.chef/context"))).to eq "staging\n"
+ expect(File.exist?(path_to(".chef/context"))).to be_falsey
+ end
+ end
+
+ context "with $KNIFE_HOME" do
+ let(:cmd_args) { %w{development} }
+ before { ENV["KNIFE_HOME"] = path_to("knifehome"); file("knifehome/tmp", "") }
+ it do
+ is_expected.to eq "Set default profile to development\n"
+ expect(File.read(path_to("knifehome/.chef/context"))).to eq "development\n"
+ expect(File.exist?(path_to(".chef/context"))).to be_falsey
+ end
+ end
+end
diff --git a/spec/integration/knife/cookbook_api_ipv6_spec.rb b/spec/integration/knife/cookbook_api_ipv6_spec.rb
index 0a4a6a6e94..8c2b0208ae 100644
--- a/spec/integration/knife/cookbook_api_ipv6_spec.rb
+++ b/spec/integration/knife/cookbook_api_ipv6_spec.rb
@@ -23,37 +23,37 @@ 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
------BEGIN RSA PRIVATE KEY-----
-MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
-0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
-NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
-0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
-AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
-HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
-8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
-zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
-k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
-i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
-G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
-ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
-awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
-7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
-g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
-Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
-HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
-V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
-fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
-lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
-c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
-fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
-YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
-syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
-+vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
------END RSA PRIVATE KEY-----
+ <<~END_VALIDATION_PEM
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf
+ 0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk
+ NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn
+ 0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O
+ AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP
+ HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom
+ 8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB
+ zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx
+ k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb
+ i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ
+ G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV
+ ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL
+ awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK
+ 7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns
+ g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr
+ Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy
+ HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2
+ V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO
+ fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN
+ lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr
+ c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo
+ fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV
+ YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL
+ syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T
+ +vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA=
+ -----END RSA PRIVATE KEY-----
END_VALIDATION_PEM
end
@@ -74,12 +74,12 @@ END_VALIDATION_PEM
when_the_repository "has the cookbook to be uploaded" do
let(:knife_rb_content) do
- <<-END_CLIENT_RB
-chef_server_url "http://[::1]:8900"
-syntax_check_cache_path '#{cache_path}'
-client_key '#{path_to('config/knifeuser.pem')}'
-node_name 'whoisthisis'
-cookbook_path '#{CHEF_SPEC_DATA}/cookbooks'
+ <<~END_CLIENT_RB
+ chef_server_url "http://[::1]:8900"
+ syntax_check_cache_path '#{cache_path}'
+ client_key '#{path_to('config/knifeuser.pem')}'
+ node_name 'whoisthisis'
+ cookbook_path '#{CHEF_SPEC_DATA}/cookbooks'
END_CLIENT_RB
end
@@ -89,7 +89,7 @@ END_CLIENT_RB
end
it "successfully uploads a cookbook" do
- shell_out!("#{knife} cookbook upload apache2 #{knife_config_flag}", :cwd => chef_dir)
+ shell_out!("#{knife} cookbook upload apache2 #{knife_config_flag}", cwd: chef_dir)
versions_list_json = Chef::HTTP::Simple.new("http://[::1]:8900").get("/cookbooks/apache2", "accept" => "application/json")
versions_list = Chef::JSONCompat.from_json(versions_list_json)
expect(versions_list["apache2"]["versions"]).not_to be_empty
@@ -97,11 +97,11 @@ END_CLIENT_RB
context "and the cookbook has been uploaded to the server" do
before do
- shell_out!("#{knife} cookbook upload apache2 #{knife_config_flag}", :cwd => chef_dir)
+ shell_out!("#{knife} cookbook upload apache2 #{knife_config_flag}", cwd: chef_dir)
end
it "downloads the cookbook" do
- shell_out!("knife cookbook download apache2 #{knife_config_flag} -d #{cache_path}", :cwd => chef_dir)
+ 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")
end
end
diff --git a/spec/integration/knife/cookbook_bulk_delete_spec.rb b/spec/integration/knife/cookbook_bulk_delete_spec.rb
index 912bd3bed5..d3180c788f 100644
--- a/spec/integration/knife/cookbook_bulk_delete_spec.rb
+++ b/spec/integration/knife/cookbook_bulk_delete_spec.rb
@@ -36,26 +36,26 @@ describe "knife cookbook bulk delete", :workstation do
# rubocop:disable Layout/TrailingWhitespace
it "knife cookbook bulk delete deletes all matching cookbooks" do
- stdout = <<EOM
-All versions of the following cookbooks will be deleted:
-
-foo fox
-
-Do you really want to delete these cookbooks? (Y/N)
+ stdout = <<~EOM
+ All versions of the following cookbooks will be deleted:
+
+ foo fox
+
+ Do you really want to delete these cookbooks? (Y/N)
EOM
- stderr = <<EOM
-Deleted cookbook foo [1.0.0]
-Deleted cookbook foo [0.6.5]
-Deleted cookbook fox [0.6.5]
-Deleted cookbook fox [0.6.0]
+ stderr = <<~EOM
+ Deleted cookbook foo [1.0.0]
+ Deleted cookbook foo [0.6.5]
+ Deleted cookbook fox [0.6.5]
+ Deleted cookbook fox [0.6.0]
EOM
knife("cookbook bulk delete ^fo.*", input: "Y").should_succeed(stderr: stderr, stdout: stdout)
- knife("cookbook list -a").should_succeed <<EOM
-fax 0.6.0
-zfa 0.6.5
+ knife("cookbook list -a").should_succeed <<~EOM
+ fax 0.6.0
+ zfa 0.6.5
EOM
end
# rubocop:enable Layout/TrailingWhitespace
diff --git a/spec/integration/knife/cookbook_download_spec.rb b/spec/integration/knife/cookbook_download_spec.rb
index 2e64cac133..57174a1548 100644
--- a/spec/integration/knife/cookbook_download_spec.rb
+++ b/spec/integration/knife/cookbook_download_spec.rb
@@ -33,18 +33,18 @@ describe "knife cookbook download", :workstation do
end
it "knife cookbook download downloads the latest version" do
- knife("cookbook download -d #{tmpdir} x").should_succeed stderr: <<EOM
-Downloading x cookbook version 1.0.1
-Downloading root_files
-Cookbook downloaded to #{tmpdir}/x-1.0.1
+ knife("cookbook download -d #{tmpdir} x").should_succeed stderr: <<~EOM
+ Downloading x cookbook version 1.0.1
+ Downloading root_files
+ Cookbook downloaded to #{tmpdir}/x-1.0.1
EOM
end
it "knife cookbook download with a version downloads the specified version" do
- knife("cookbook download -d #{tmpdir} x 1.0.1").should_succeed stderr: <<EOM
-Downloading x cookbook version 1.0.1
-Downloading root_files
-Cookbook downloaded to #{tmpdir}/x-1.0.1
+ knife("cookbook download -d #{tmpdir} x 1.0.1").should_succeed stderr: <<~EOM
+ Downloading x cookbook version 1.0.1
+ Downloading root_files
+ Cookbook downloaded to #{tmpdir}/x-1.0.1
EOM
end
@@ -60,10 +60,10 @@ EOM
end
it "knife cookbook download with no version prompts" do
- knife("cookbook download -d #{tmpdir} x", input: "2\n").should_succeed(stderr: <<EOM, stdout: "Which version do you want to download?\n1. x 1.0.0\n2. x 1.0.1\n\n"
-Downloading x cookbook version 1.0.1
-Downloading root_files
-Cookbook downloaded to #{tmpdir}/x-1.0.1
+ knife("cookbook download -d #{tmpdir} x", input: "2\n").should_succeed(stderr: <<~EOM, stdout: "Which version do you want to download?\n1. x 1.0.0\n2. x 1.0.1\n\n"
+ Downloading x cookbook version 1.0.1
+ Downloading root_files
+ Cookbook downloaded to #{tmpdir}/x-1.0.1
EOM
)
end
diff --git a/spec/integration/knife/cookbook_list_spec.rb b/spec/integration/knife/cookbook_list_spec.rb
index 65578696f2..afea745bce 100644
--- a/spec/integration/knife/cookbook_list_spec.rb
+++ b/spec/integration/knife/cookbook_list_spec.rb
@@ -35,18 +35,18 @@ describe "knife cookbook list", :workstation do
end
it "knife cookbook list shows all the cookbooks" do
- knife("cookbook list").should_succeed <<EOM
-x 1.0.0
-y 0.6.5
-z 0.6.5
+ knife("cookbook list").should_succeed <<~EOM
+ x 1.0.0
+ y 0.6.5
+ z 0.6.5
EOM
end
it "knife cookbook list -a shows all the versions of all the cookbooks" do
- knife("cookbook list -a").should_succeed <<EOM
-x 1.0.0 0.6.5 0.6.0
-y 0.6.5 0.6.0
-z 0.6.5
+ knife("cookbook list -a").should_succeed <<~EOM
+ x 1.0.0 0.6.5 0.6.0
+ y 0.6.5 0.6.0
+ z 0.6.5
EOM
end
diff --git a/spec/integration/knife/cookbook_show_spec.rb b/spec/integration/knife/cookbook_show_spec.rb
index b89a26198a..fe7e6fa930 100644
--- a/spec/integration/knife/cookbook_show_spec.rb
+++ b/spec/integration/knife/cookbook_show_spec.rb
@@ -36,95 +36,95 @@ describe "knife cookbook show", :workstation do
# rubocop:disable Layout/TrailingWhitespace
it "knife cookbook show x 1.0.0 shows the correct version" do
- knife("cookbook show x 1.0.0").should_succeed <<EOM
-cookbook_name: x
-frozen?: false
-metadata:
- attributes:
- chef_versions:
- dependencies:
- description:
- gems:
- issues_url:
- license: All rights reserved
- long_description:
- maintainer:
- maintainer_email:
- name: x
- ohai_versions:
- platforms:
- privacy: false
- providing:
- x: >= 0.0.0
- x::x: >= 0.0.0
- recipes:
- x:
- x::x:
- source_url:
- version: 1.0.0
-name: x-1.0.0
-recipes:
- checksum: 4631b34cf58de10c5ef1304889941b2e
- name: recipes/default.rb
- path: recipes/default.rb
- specificity: default
- url: http://127.0.0.1:8900/file_store/checksums/4631b34cf58de10c5ef1304889941b2e
-
- checksum: d41d8cd98f00b204e9800998ecf8427e
- name: recipes/x.rb
- path: recipes/x.rb
- specificity: default
- url: http://127.0.0.1:8900/file_store/checksums/d41d8cd98f00b204e9800998ecf8427e
-root_files:
- checksum: 8226671f751ba102dea6a6b6bd32fa8d
- name: metadata.rb
- path: metadata.rb
- specificity: default
- url: http://127.0.0.1:8900/file_store/checksums/8226671f751ba102dea6a6b6bd32fa8d
-version: 1.0.0
+ knife("cookbook show x 1.0.0").should_succeed <<~EOM
+ cookbook_name: x
+ frozen?: false
+ metadata:
+ attributes:
+ chef_versions:
+ dependencies:
+ description:
+ gems:
+ issues_url:
+ license: All rights reserved
+ long_description:
+ maintainer:
+ maintainer_email:
+ name: x
+ ohai_versions:
+ platforms:
+ privacy: false
+ providing:
+ x: >= 0.0.0
+ x::x: >= 0.0.0
+ recipes:
+ x:
+ x::x:
+ source_url:
+ version: 1.0.0
+ name: x-1.0.0
+ recipes:
+ checksum: 4631b34cf58de10c5ef1304889941b2e
+ name: recipes/default.rb
+ path: recipes/default.rb
+ specificity: default
+ url: http://127.0.0.1:8900/file_store/checksums/4631b34cf58de10c5ef1304889941b2e
+
+ checksum: d41d8cd98f00b204e9800998ecf8427e
+ name: recipes/x.rb
+ path: recipes/x.rb
+ specificity: default
+ url: http://127.0.0.1:8900/file_store/checksums/d41d8cd98f00b204e9800998ecf8427e
+ root_files:
+ checksum: 8226671f751ba102dea6a6b6bd32fa8d
+ name: metadata.rb
+ path: metadata.rb
+ specificity: default
+ url: http://127.0.0.1:8900/file_store/checksums/8226671f751ba102dea6a6b6bd32fa8d
+ version: 1.0.0
EOM
end
it "knife cookbook show x 1.0.0 metadata shows the metadata" do
- knife("cookbook show x 1.0.0 metadata").should_succeed <<EOM
-attributes:
-chef_versions:
-dependencies:
-description:
-gems:
-issues_url:
-license: All rights reserved
-long_description:
-maintainer:
-maintainer_email:
-name: x
-ohai_versions:
-platforms:
-privacy: false
-providing:
- x: >= 0.0.0
- x::x: >= 0.0.0
-recipes:
- x:
- x::x:
-source_url:
-version: 1.0.0
+ knife("cookbook show x 1.0.0 metadata").should_succeed <<~EOM
+ attributes:
+ chef_versions:
+ dependencies:
+ description:
+ gems:
+ issues_url:
+ license: All rights reserved
+ long_description:
+ maintainer:
+ maintainer_email:
+ name: x
+ ohai_versions:
+ platforms:
+ privacy: false
+ providing:
+ x: >= 0.0.0
+ x::x: >= 0.0.0
+ recipes:
+ x:
+ x::x:
+ source_url:
+ version: 1.0.0
EOM
end
it "knife cookbook show x 1.0.0 recipes shows all the recipes" do
- knife("cookbook show x 1.0.0 recipes").should_succeed <<EOM
-checksum: 4631b34cf58de10c5ef1304889941b2e
-name: recipes/default.rb
-path: recipes/default.rb
-specificity: default
-url: http://127.0.0.1:8900/file_store/checksums/4631b34cf58de10c5ef1304889941b2e
-
-checksum: d41d8cd98f00b204e9800998ecf8427e
-name: recipes/x.rb
-path: recipes/x.rb
-specificity: default
-url: http://127.0.0.1:8900/file_store/checksums/d41d8cd98f00b204e9800998ecf8427e
+ knife("cookbook show x 1.0.0 recipes").should_succeed <<~EOM
+ checksum: 4631b34cf58de10c5ef1304889941b2e
+ name: recipes/default.rb
+ path: recipes/default.rb
+ specificity: default
+ url: http://127.0.0.1:8900/file_store/checksums/4631b34cf58de10c5ef1304889941b2e
+
+ checksum: d41d8cd98f00b204e9800998ecf8427e
+ name: recipes/x.rb
+ path: recipes/x.rb
+ specificity: default
+ url: http://127.0.0.1:8900/file_store/checksums/d41d8cd98f00b204e9800998ecf8427e
EOM
end
# rubocop:enable Layout/TrailingWhitespace
diff --git a/spec/integration/knife/cookbook_upload_spec.rb b/spec/integration/knife/cookbook_upload_spec.rb
index a0de725603..e96884e786 100644
--- a/spec/integration/knife/cookbook_upload_spec.rb
+++ b/spec/integration/knife/cookbook_upload_spec.rb
@@ -33,24 +33,24 @@ describe "knife cookbook upload", :workstation do
end
it "knife cookbook upload uploads the cookbook" do
- knife("cookbook upload x -o #{cb_dir}").should_succeed stderr: <<EOM
-Uploading x [1.0.0]
-Uploaded 1 cookbook.
+ knife("cookbook upload x -o #{cb_dir}").should_succeed stderr: <<~EOM
+ Uploading x [1.0.0]
+ Uploaded 1 cookbook.
EOM
end
it "knife cookbook upload --freeze uploads and freezes the cookbook" do
- knife("cookbook upload x -o #{cb_dir} --freeze").should_succeed stderr: <<EOM
-Uploading x [1.0.0]
-Uploaded 1 cookbook.
+ knife("cookbook upload x -o #{cb_dir} --freeze").should_succeed stderr: <<~EOM
+ Uploading x [1.0.0]
+ Uploaded 1 cookbook.
EOM
# Modify the file, attempt to reupload
file "cookbooks/x/metadata.rb", 'name "x"; version "1.0.0"#different'
- knife("cookbook upload x -o #{cb_dir} --freeze").should_fail stderr: <<EOM
-Uploading x [1.0.0]
-ERROR: Version 1.0.0 of cookbook x is frozen. Use --force to override.
-WARNING: Not updating version constraints for x in the environment as the cookbook is frozen.
-ERROR: Failed to upload 1 cookbook.
+ knife("cookbook upload x -o #{cb_dir} --freeze").should_fail stderr: <<~EOM
+ Uploading x [1.0.0]
+ ERROR: Version 1.0.0 of cookbook x is frozen. Use --force to override.
+ WARNING: Not updating version constraints for x in the environment as the cookbook is frozen.
+ ERROR: Failed to upload 1 cookbook.
EOM
end
end
@@ -62,27 +62,27 @@ EOM
end
it "knife cookbook upload --include-dependencies uploads both cookbooks" do
- knife("cookbook upload --include-dependencies x -o #{cb_dir}").should_succeed stderr: <<EOM
-Uploading x [1.0.0]
-Uploading y [1.0.0]
-Uploaded 2 cookbooks.
+ knife("cookbook upload --include-dependencies x -o #{cb_dir}").should_succeed stderr: <<~EOM
+ Uploading x [1.0.0]
+ Uploading y [1.0.0]
+ Uploaded 2 cookbooks.
EOM
end
it "knife cookbook upload fails due to missing dependencies" do
- knife("cookbook upload x -o #{cb_dir}").should_fail stderr: <<EOM
-Uploading x [1.0.0]
-ERROR: Cookbook x depends on cookbooks which are not currently
-ERROR: being uploaded and cannot be found on the server.
-ERROR: The missing cookbook(s) are: 'y' version '>= 0.0.0'
+ knife("cookbook upload x -o #{cb_dir}").should_fail stderr: <<~EOM
+ Uploading x [1.0.0]
+ ERROR: Cookbook x depends on cookbooks which are not currently
+ ERROR: being uploaded and cannot be found on the server.
+ ERROR: The missing cookbook(s) are: 'y' version '>= 0.0.0'
EOM
end
it "knife cookbook upload -a uploads both cookbooks" do
- knife("cookbook upload -a -o #{cb_dir}").should_succeed stderr: <<EOM
-Uploading x [1.0.0]
-Uploading y [1.0.0]
-Uploaded all cookbooks.
+ knife("cookbook upload -a -o #{cb_dir}").should_succeed stderr: <<~EOM
+ Uploading x [1.0.0]
+ Uploading y [1.0.0]
+ Uploaded all cookbooks.
EOM
end
end
diff --git a/spec/integration/knife/data_bag_delete_spec.rb b/spec/integration/knife/data_bag_delete_spec.rb
index 96345b0d2b..f0ca05a3e4 100644
--- a/spec/integration/knife/data_bag_delete_spec.rb
+++ b/spec/integration/knife/data_bag_delete_spec.rb
@@ -32,26 +32,26 @@ describe "knife data bag delete", :workstation do
end
it "with an empty data bag" do
- knife("data bag delete canteloupe", input: "y").should_succeed <<EOM
-Do you really want to delete canteloupe? (Y/N) Deleted data_bag[canteloupe]
+ knife("data bag delete canteloupe", input: "y").should_succeed <<~EOM
+ Do you really want to delete canteloupe? (Y/N) Deleted data_bag[canteloupe]
EOM
end
it "with a bag with some items" do
- knife("data bag delete rocket", input: "y").should_succeed <<EOM
-Do you really want to delete rocket? (Y/N) Deleted data_bag[rocket]
+ knife("data bag delete rocket", input: "y").should_succeed <<~EOM
+ Do you really want to delete rocket? (Y/N) Deleted data_bag[rocket]
EOM
end
it "with a single item" do
- knife("data bag delete rocket falcon9", input: "y").should_succeed <<EOM
-Do you really want to delete falcon9? (Y/N) Deleted data_bag_item[falcon9]
+ knife("data bag delete rocket falcon9", input: "y").should_succeed <<~EOM
+ Do you really want to delete falcon9? (Y/N) Deleted data_bag_item[falcon9]
EOM
end
it "choosing not to delete" do
- knife("data bag delete rocket falcon9", input: "n").should_succeed <<EOM, exit_code: 3
-Do you really want to delete falcon9? (Y/N) You said no, so I'm done here.
+ knife("data bag delete rocket falcon9", input: "n").should_succeed <<~EOM, exit_code: 3
+ Do you really want to delete falcon9? (Y/N) You said no, so I'm done here.
EOM
end
end
diff --git a/spec/integration/knife/data_bag_from_file_spec.rb b/spec/integration/knife/data_bag_from_file_spec.rb
index ca8f743487..afaafc1e6b 100644
--- a/spec/integration/knife/data_bag_from_file_spec.rb
+++ b/spec/integration/knife/data_bag_from_file_spec.rb
@@ -37,76 +37,76 @@ describe "knife data bag from file", :workstation do
file "data_bags/foo/bzr.json", { "id" => "bzr", "foo" => "bar " }
file "data_bags/foo/cat.json", { "id" => "cat", "foo" => "bar " }
file "data_bags/foo/dog.json", { "id" => "dog", "foo" => "bar " }
- file "data_bags/foo/encrypted.json", <<EOM
-{
- "id": "encrypted",
- "password": {
- "encrypted_data": "H6ab5RY9a9JAkS8A0RCMspXtOJh0ai8cNeA4Q3gLO8s=\\n",
- "iv": "uWKKKxrJgtELlGMCOLJdkA==\\n",
- "version": 1,
- "cipher": "aes-256-cbc"
- }
-}
+ file "data_bags/foo/encrypted.json", <<~EOM
+ {
+ "id": "encrypted",
+ "password": {
+ "encrypted_data": "H6ab5RY9a9JAkS8A0RCMspXtOJh0ai8cNeA4Q3gLO8s=\\n",
+ "iv": "uWKKKxrJgtELlGMCOLJdkA==\\n",
+ "version": 1,
+ "cipher": "aes-256-cbc"
+ }
+ }
EOM
- file "data_bags/bar/round_trip.json", <<EOM
-{
- "name": "data_bag_item_bar_round_trip",
- "json_class": "Chef::DataBagItem",
- "chef_type": "data_bag_item",
- "data_bag": "bar",
- "raw_data": {
- "id": "round_trip",
- "root_password": {
- "encrypted_data": "noDOsTpsTAZlTU5sprhmYZzUDfr8du7hH/zRDOjRAmoTJHTZyfYoR221EOOW\\nXJ1D\\n",
- "iv": "Bnqhfy6n0Hx1wCe9pxHLoA==\\n",
- "version": 1,
- "cipher": "aes-256-cbc"
- },
- "admin_password": {
- "encrypted_data": "TcC7dU1gx6OnE5Ab4i/k42UEf0Nnr7cAyuTHId/LNjNOwpNf7XZc27DQSjuy\\nHPlt\\n",
- "iv": "+TAWJuPWCI2+WB8lGJAyvw==\\n",
- "version": 1,
- "cipher": "aes-256-cbc"
- }
- }
-}
+ file "data_bags/bar/round_trip.json", <<~EOM
+ {
+ "name": "data_bag_item_bar_round_trip",
+ "json_class": "Chef::DataBagItem",
+ "chef_type": "data_bag_item",
+ "data_bag": "bar",
+ "raw_data": {
+ "id": "round_trip",
+ "root_password": {
+ "encrypted_data": "noDOsTpsTAZlTU5sprhmYZzUDfr8du7hH/zRDOjRAmoTJHTZyfYoR221EOOW\\nXJ1D\\n",
+ "iv": "Bnqhfy6n0Hx1wCe9pxHLoA==\\n",
+ "version": 1,
+ "cipher": "aes-256-cbc"
+ },
+ "admin_password": {
+ "encrypted_data": "TcC7dU1gx6OnE5Ab4i/k42UEf0Nnr7cAyuTHId/LNjNOwpNf7XZc27DQSjuy\\nHPlt\\n",
+ "iv": "+TAWJuPWCI2+WB8lGJAyvw==\\n",
+ "version": 1,
+ "cipher": "aes-256-cbc"
+ }
+ }
+ }
EOM
end
it "uploads a single file" do
- knife("data bag from file foo #{db_dir}/foo/bar.json").should_succeed stderr: <<EOM
-Updated data_bag_item[foo::bar]
+ knife("data bag from file foo #{db_dir}/foo/bar.json").should_succeed stderr: <<~EOM
+ Updated data_bag_item[foo::bar]
EOM
end
it "uploads a single encrypted file" do
- knife("data bag from file foo #{db_dir}/foo/encrypted.json").should_succeed stderr: <<EOM
-Updated data_bag_item[foo::encrypted]
+ knife("data bag from file foo #{db_dir}/foo/encrypted.json").should_succeed stderr: <<~EOM
+ Updated data_bag_item[foo::encrypted]
EOM
end
it "uploads a file in chef's internal format" do
pending "chef/chef#4815"
- knife("data bag from file bar #{db_dir}/bar/round_trip.json").should_succeed stderr: <<EOM
-Updated data_bag_item[bar::round_trip]
+ knife("data bag from file bar #{db_dir}/bar/round_trip.json").should_succeed stderr: <<~EOM
+ Updated data_bag_item[bar::round_trip]
EOM
end
it "uploads many files" do
- knife("data bag from file foo #{db_dir}/foo/bar.json #{db_dir}/foo/bzr.json").should_succeed stderr: <<EOM
-Updated data_bag_item[foo::bar]
-Updated data_bag_item[foo::bzr]
+ knife("data bag from file foo #{db_dir}/foo/bar.json #{db_dir}/foo/bzr.json").should_succeed stderr: <<~EOM
+ Updated data_bag_item[foo::bar]
+ Updated data_bag_item[foo::bzr]
EOM
end
it "uploads a whole directory" do
knife("data bag from file foo #{db_dir}/foo")
- knife("data bag show foo").should_succeed <<EOM
-bar
-bzr
-cat
-dog
-encrypted
+ knife("data bag show foo").should_succeed <<~EOM
+ bar
+ bzr
+ cat
+ dog
+ encrypted
EOM
end
diff --git a/spec/integration/knife/data_bag_list_spec.rb b/spec/integration/knife/data_bag_list_spec.rb
index 7db9638660..4a2b740937 100644
--- a/spec/integration/knife/data_bag_list_spec.rb
+++ b/spec/integration/knife/data_bag_list_spec.rb
@@ -32,10 +32,10 @@ describe "knife data bag list", :workstation do
end
it "knife data bag list shows all the cookbooks" do
- knife("data bag list").should_succeed <<EOM
-canteloupe
-rocket
-x
+ knife("data bag list").should_succeed <<~EOM
+ canteloupe
+ rocket
+ x
EOM
end
diff --git a/spec/integration/knife/data_bag_show_spec.rb b/spec/integration/knife/data_bag_show_spec.rb
index 22381adb9e..5fefec5266 100644
--- a/spec/integration/knife/data_bag_show_spec.rb
+++ b/spec/integration/knife/data_bag_show_spec.rb
@@ -36,17 +36,17 @@ describe "knife data bag show", :workstation do
end
it "with a bag with some items" do
- knife("data bag show rocket").should_succeed <<EOM
-ariane
-atlas
-falcon9
+ knife("data bag show rocket").should_succeed <<~EOM
+ ariane
+ atlas
+ falcon9
EOM
end
it "with a single item" do
- knife("data bag show rocket falcon9").should_succeed <<EOM, stderr: "WARNING: Unencrypted data bag detected, ignoring any provided secret options.\n"
-heavy: true
-id: falcon9
+ knife("data bag show rocket falcon9").should_succeed <<~EOM
+ heavy: true
+ id: falcon9
EOM
end
end
diff --git a/spec/integration/knife/delete_spec.rb b/spec/integration/knife/delete_spec.rb
index 1c69fbf9c9..2e3efcf693 100644
--- a/spec/integration/knife/delete_spec.rb
+++ b/spec/integration/knife/delete_spec.rb
@@ -25,76 +25,76 @@ describe "knife delete", :workstation do
include KnifeSupport
let :everything do
- <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
let :server_everything do
- <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
+ <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
EOM
end
let :server_nothing do
- <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/cookbooks
-/data_bags
-/environments
-/environments/_default.json
-/nodes
-/roles
-/users
-/users/admin.json
+ <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /cookbooks
+ /data_bags
+ /environments
+ /environments/_default.json
+ /nodes
+ /roles
+ /users
+ /users/admin.json
EOM
end
let :nothing do
- <<EOM
-/clients
-/cookbooks
-/data_bags
-/environments
-/nodes
-/roles
-/users
+ <<~EOM
+ /clients
+ /cookbooks
+ /data_bags
+ /environments
+ /nodes
+ /roles
+ /users
EOM
end
@@ -122,9 +122,9 @@ EOM
end
it "knife delete --both /cookbooks/x fails" do
- knife("delete --both /cookbooks/x").should_fail <<EOM
-ERROR: /cookbooks/x (remote) must be deleted recursively! Pass -r to knife delete.
-ERROR: /cookbooks/x (local) must be deleted recursively! Pass -r to knife delete.
+ knife("delete --both /cookbooks/x").should_fail <<~EOM
+ ERROR: /cookbooks/x (remote) must be deleted recursively! Pass -r to knife delete.
+ ERROR: /cookbooks/x (local) must be deleted recursively! Pass -r to knife delete.
EOM
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed everything
@@ -132,88 +132,88 @@ EOM
it "knife delete --both -r /cookbooks/x deletes x" do
knife("delete --both -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete -r --local /cookbooks/x deletes x locally but not remotely" do
knife("delete -r --local /cookbooks/x").should_succeed "Deleted /cookbooks/x\n"
knife("list -Rf /").should_succeed server_everything
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete -r /cookbooks/x deletes x remotely but not locally" do
knife("delete -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
EOM
knife("list -Rf --local /").should_succeed everything
end
@@ -226,60 +226,60 @@ EOM
end
it "knife delete --both /data_bags/empty fails but deletes local version" do
- knife("delete --both /data_bags/empty").should_fail <<EOM
-ERROR: /data_bags/empty (remote) must be deleted recursively! Pass -r to knife delete.
-ERROR: /data_bags/empty (local) must be deleted recursively! Pass -r to knife delete.
-EOM
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/empty
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/empty
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("delete --both /data_bags/empty").should_fail <<~EOM
+ ERROR: /data_bags/empty (remote) must be deleted recursively! Pass -r to knife delete.
+ ERROR: /data_bags/empty (local) must be deleted recursively! Pass -r to knife delete.
+EOM
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/empty
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/empty
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
end
it "knife delete --both /data_bags/x fails" do
- knife("delete --both /data_bags/x").should_fail <<EOM
-ERROR: /data_bags/x (remote) must be deleted recursively! Pass -r to knife delete.
-ERROR: /data_bags/x (local) must be deleted recursively! Pass -r to knife delete.
+ knife("delete --both /data_bags/x").should_fail <<~EOM
+ ERROR: /data_bags/x (remote) must be deleted recursively! Pass -r to knife delete.
+ ERROR: /data_bags/x (local) must be deleted recursively! Pass -r to knife delete.
EOM
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed everything
@@ -287,151 +287,151 @@ EOM
it "knife delete --both -r /data_bags/x deletes x" do
knife("delete --both -r /data_bags/x").should_succeed "Deleted /data_bags/x\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /environments/x.json deletes x" do
knife("delete --both /environments/x.json").should_succeed "Deleted /environments/x.json\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /roles/x.json deletes x" do
knife("delete --both /roles/x.json").should_succeed "Deleted /roles/x.json\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/users
-/users/admin.json
-/users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/users
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /users
+ /users/admin.json
+ /users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /environments/_default.json fails but still deletes the local copy" do
- knife("delete --both /environments/_default.json").should_fail :stderr => "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n", :stdout => "Deleted /environments/_default.json\n"
+ knife("delete --both /environments/_default.json").should_fail stderr: "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n", stdout: "Deleted /environments/_default.json\n"
knife("list -Rf /").should_succeed server_everything
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
@@ -442,32 +442,32 @@ EOM
end
it "knife delete --both / fails" do
- knife("delete --both /").should_fail <<EOM
-ERROR: / (remote) cannot be deleted.
-ERROR: / (local) cannot be deleted.
+ knife("delete --both /").should_fail <<~EOM
+ ERROR: / (remote) cannot be deleted.
+ ERROR: / (local) cannot be deleted.
EOM
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed everything
end
it "knife delete --both -r /* fails" do
- knife("delete --both -r /*").should_fail <<EOM
-ERROR: / (remote) cannot be deleted.
-ERROR: / (local) cannot be deleted.
-ERROR: /clients (remote) cannot be deleted.
-ERROR: /clients (local) cannot be deleted.
-ERROR: /cookbooks (remote) cannot be deleted.
-ERROR: /cookbooks (local) cannot be deleted.
-ERROR: /data_bags (remote) cannot be deleted.
-ERROR: /data_bags (local) cannot be deleted.
-ERROR: /environments (remote) cannot be deleted.
-ERROR: /environments (local) cannot be deleted.
-ERROR: /nodes (remote) cannot be deleted.
-ERROR: /nodes (local) cannot be deleted.
-ERROR: /roles (remote) cannot be deleted.
-ERROR: /roles (local) cannot be deleted.
-ERROR: /users (remote) cannot be deleted.
-ERROR: /users (local) cannot be deleted.
+ knife("delete --both -r /*").should_fail <<~EOM
+ ERROR: / (remote) cannot be deleted.
+ ERROR: / (local) cannot be deleted.
+ ERROR: /clients (remote) cannot be deleted.
+ ERROR: /clients (local) cannot be deleted.
+ ERROR: /cookbooks (remote) cannot be deleted.
+ ERROR: /cookbooks (local) cannot be deleted.
+ ERROR: /data_bags (remote) cannot be deleted.
+ ERROR: /data_bags (local) cannot be deleted.
+ ERROR: /environments (remote) cannot be deleted.
+ ERROR: /environments (local) cannot be deleted.
+ ERROR: /nodes (remote) cannot be deleted.
+ ERROR: /nodes (local) cannot be deleted.
+ ERROR: /roles (remote) cannot be deleted.
+ ERROR: /roles (local) cannot be deleted.
+ ERROR: /users (remote) cannot be deleted.
+ ERROR: /users (local) cannot be deleted.
EOM
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed everything
@@ -493,25 +493,25 @@ EOM
it "knife delete --both -r /cookbooks/x deletes x" do
knife("delete --both -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
EOM
knife("list -Rf --local /").should_succeed nothing
end
@@ -524,83 +524,83 @@ EOM
it "knife delete --both -r /data_bags/x deletes x" do
knife("delete --both -r /data_bags/x").should_succeed "Deleted /data_bags/x\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
EOM
knife("list -Rf --local /").should_succeed nothing
end
it "knife delete --both /environments/x.json deletes x" do
knife("delete --both /environments/x.json").should_succeed "Deleted /environments/x.json\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/admin.json
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/admin.json
+ /users/x.json
EOM
knife("list -Rf --local /").should_succeed nothing
end
it "knife delete --both /roles/x.json deletes x" do
knife("delete --both /roles/x.json").should_succeed "Deleted /roles/x.json\n"
- knife("list -Rf /").should_succeed <<EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/users
-/users/admin.json
-/users/x.json
+ knife("list -Rf /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /users
+ /users/admin.json
+ /users/x.json
EOM
knife("list -Rf --local /").should_succeed nothing
end
it "knife delete --both /environments/_default.json fails" do
- knife("delete --both /environments/_default.json").should_fail "", :stderr => "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n"
+ knife("delete --both /environments/_default.json").should_fail "", stderr: "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n"
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed nothing
end
@@ -612,23 +612,23 @@ EOM
end
it "knife delete --both -r /* fails" do
- knife("delete --both -r /*").should_fail <<EOM
-ERROR: / (remote) cannot be deleted.
-ERROR: / (local) cannot be deleted.
-ERROR: /clients (remote) cannot be deleted.
-ERROR: /clients (local) cannot be deleted.
-ERROR: /cookbooks (remote) cannot be deleted.
-ERROR: /cookbooks (local) cannot be deleted.
-ERROR: /data_bags (remote) cannot be deleted.
-ERROR: /data_bags (local) cannot be deleted.
-ERROR: /environments (remote) cannot be deleted.
-ERROR: /environments (local) cannot be deleted.
-ERROR: /nodes (remote) cannot be deleted.
-ERROR: /nodes (local) cannot be deleted.
-ERROR: /roles (remote) cannot be deleted.
-ERROR: /roles (local) cannot be deleted.
-ERROR: /users (remote) cannot be deleted.
-ERROR: /users (local) cannot be deleted.
+ knife("delete --both -r /*").should_fail <<~EOM
+ ERROR: / (remote) cannot be deleted.
+ ERROR: / (local) cannot be deleted.
+ ERROR: /clients (remote) cannot be deleted.
+ ERROR: /clients (local) cannot be deleted.
+ ERROR: /cookbooks (remote) cannot be deleted.
+ ERROR: /cookbooks (local) cannot be deleted.
+ ERROR: /data_bags (remote) cannot be deleted.
+ ERROR: /data_bags (local) cannot be deleted.
+ ERROR: /environments (remote) cannot be deleted.
+ ERROR: /environments (local) cannot be deleted.
+ ERROR: /nodes (remote) cannot be deleted.
+ ERROR: /nodes (local) cannot be deleted.
+ ERROR: /roles (remote) cannot be deleted.
+ ERROR: /roles (local) cannot be deleted.
+ ERROR: /users (remote) cannot be deleted.
+ ERROR: /users (local) cannot be deleted.
EOM
knife("list -Rf /").should_succeed server_everything
knife("list -Rf --local /").should_succeed nothing
@@ -643,37 +643,37 @@ EOM
context "and cwd is at the top level" do
before { cwd "." }
it "knife delete fails" do
- knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", :stdout => /USAGE/
- knife("list -Rf /").should_succeed <<EOM
-clients
-clients/chef-validator.json
-clients/chef-webui.json
-clients/x.json
-cookbooks
-cookbooks/x
-cookbooks/x/metadata.rb
-data_bags
-data_bags/x
-data_bags/x/y.json
-environments
-environments/_default.json
-environments/x.json
-nodes
-nodes/x.json
-roles
-roles/x.json
-users
-users/admin.json
-users/x.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-clients
-cookbooks
-data_bags
-environments
-nodes
-roles
-users
+ knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", stdout: /USAGE/
+ knife("list -Rf /").should_succeed <<~EOM
+ clients
+ clients/chef-validator.json
+ clients/chef-webui.json
+ clients/x.json
+ cookbooks
+ cookbooks/x
+ cookbooks/x/metadata.rb
+ data_bags
+ data_bags/x
+ data_bags/x/y.json
+ environments
+ environments/_default.json
+ environments/x.json
+ nodes
+ nodes/x.json
+ roles
+ roles/x.json
+ users
+ users/admin.json
+ users/x.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ clients
+ cookbooks
+ data_bags
+ environments
+ nodes
+ roles
+ users
EOM
end
end
@@ -702,22 +702,22 @@ EOM
it "knife delete --both -r /cookbooks/x deletes x" do
knife("delete --both -r /cookbooks/x").should_succeed "Deleted /cookbooks/x\n"
knife("list -Rf /").should_succeed server_nothing
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
@@ -730,91 +730,91 @@ EOM
it "knife delete --both -r /data_bags/x deletes x" do
knife("delete --both -r /data_bags/x").should_succeed "Deleted /data_bags/x\n"
knife("list -Rf /").should_succeed server_nothing
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /environments/x.json deletes x" do
knife("delete --both /environments/x.json").should_succeed "Deleted /environments/x.json\n"
knife("list -Rf /").should_succeed server_nothing
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /roles/x.json deletes x" do
knife("delete --both /roles/x.json").should_succeed "Deleted /roles/x.json\n"
knife("list -Rf /").should_succeed server_nothing
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/_default.json
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/_default.json
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /users
+ /users/x.json
EOM
end
it "knife delete --both /environments/_default.json fails but still deletes the local copy" do
- knife("delete --both /environments/_default.json").should_fail :stderr => "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n", :stdout => "Deleted /environments/_default.json\n"
+ knife("delete --both /environments/_default.json").should_fail stderr: "ERROR: /environments/_default.json (remote) cannot be deleted (default environment cannot be modified).\n", stdout: "Deleted /environments/_default.json\n"
knife("list -Rf /").should_succeed server_nothing
- knife("list -Rf --local /").should_succeed <<EOM
-/clients
-/clients/x.json
-/cookbooks
-/cookbooks/x
-/cookbooks/x/metadata.rb
-/data_bags
-/data_bags/x
-/data_bags/x/y.json
-/environments
-/environments/x.json
-/nodes
-/nodes/x.json
-/roles
-/roles/x.json
-/users
-/users/x.json
+ knife("list -Rf --local /").should_succeed <<~EOM
+ /clients
+ /clients/x.json
+ /cookbooks
+ /cookbooks/x
+ /cookbooks/x/metadata.rb
+ /data_bags
+ /data_bags/x
+ /data_bags/x/y.json
+ /environments
+ /environments/x.json
+ /nodes
+ /nodes/x.json
+ /roles
+ /roles/x.json
+ /users
+ /users/x.json
EOM
end
@@ -825,23 +825,23 @@ EOM
end
it "knife delete --both -r /* fails" do
- knife("delete --both -r /*").should_fail <<EOM
-ERROR: / (remote) cannot be deleted.
-ERROR: / (local) cannot be deleted.
-ERROR: /clients (remote) cannot be deleted.
-ERROR: /clients (local) cannot be deleted.
-ERROR: /cookbooks (remote) cannot be deleted.
-ERROR: /cookbooks (local) cannot be deleted.
-ERROR: /data_bags (remote) cannot be deleted.
-ERROR: /data_bags (local) cannot be deleted.
-ERROR: /environments (remote) cannot be deleted.
-ERROR: /environments (local) cannot be deleted.
-ERROR: /nodes (remote) cannot be deleted.
-ERROR: /nodes (local) cannot be deleted.
-ERROR: /roles (remote) cannot be deleted.
-ERROR: /roles (local) cannot be deleted.
-ERROR: /users (remote) cannot be deleted.
-ERROR: /users (local) cannot be deleted.
+ knife("delete --both -r /*").should_fail <<~EOM
+ ERROR: / (remote) cannot be deleted.
+ ERROR: / (local) cannot be deleted.
+ ERROR: /clients (remote) cannot be deleted.
+ ERROR: /clients (local) cannot be deleted.
+ ERROR: /cookbooks (remote) cannot be deleted.
+ ERROR: /cookbooks (local) cannot be deleted.
+ ERROR: /data_bags (remote) cannot be deleted.
+ ERROR: /data_bags (local) cannot be deleted.
+ ERROR: /environments (remote) cannot be deleted.
+ ERROR: /environments (local) cannot be deleted.
+ ERROR: /nodes (remote) cannot be deleted.
+ ERROR: /nodes (local) cannot be deleted.
+ ERROR: /roles (remote) cannot be deleted.
+ ERROR: /roles (local) cannot be deleted.
+ ERROR: /users (remote) cannot be deleted.
+ ERROR: /users (local) cannot be deleted.
EOM
knife("list -Rf /").should_succeed server_nothing
knife("list -Rf --local /").should_succeed everything
@@ -856,38 +856,38 @@ EOM
context "and cwd is at the top level" do
before { cwd "." }
it "knife delete fails" do
- knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", :stdout => /USAGE/
- knife("list -Rf /").should_succeed <<EOM
-clients
-clients/chef-validator.json
-clients/chef-webui.json
-cookbooks
-data_bags
-environments
-environments/_default.json
-nodes
-roles
-users
-users/admin.json
-EOM
- knife("list -Rf --local /").should_succeed <<EOM
-clients
-clients/x.json
-cookbooks
-cookbooks/x
-cookbooks/x/metadata.rb
-data_bags
-data_bags/x
-data_bags/x/y.json
-environments
-environments/_default.json
-environments/x.json
-nodes
-nodes/x.json
-roles
-roles/x.json
-users
-users/x.json
+ knife("delete").should_fail "FATAL: You must specify at least one argument. If you want to delete everything in this directory, run \"knife delete --recurse .\"\n", stdout: /USAGE/
+ knife("list -Rf /").should_succeed <<~EOM
+ clients
+ clients/chef-validator.json
+ clients/chef-webui.json
+ cookbooks
+ data_bags
+ environments
+ environments/_default.json
+ nodes
+ roles
+ users
+ users/admin.json
+EOM
+ knife("list -Rf --local /").should_succeed <<~EOM
+ clients
+ clients/x.json
+ cookbooks
+ cookbooks/x
+ cookbooks/x/metadata.rb
+ data_bags
+ data_bags/x
+ data_bags/x/y.json
+ environments
+ environments/_default.json
+ environments/x.json
+ nodes
+ nodes/x.json
+ roles
+ roles/x.json
+ users
+ users/x.json
EOM
end
end
@@ -962,7 +962,7 @@ EOM
end
end
- when_the_chef_server "is in Enterprise mode", :osc_compat => false, :single_org => false do
+ when_the_chef_server "is in Enterprise mode", osc_compat: false, single_org: false do
before do
organization "foo" do
container "x", {}
diff --git a/spec/integration/knife/deps_spec.rb b/spec/integration/knife/deps_spec.rb
index 40ec411780..b7eafcbd1c 100644
--- a/spec/integration/knife/deps_spec.rb
+++ b/spec/integration/knife/deps_spec.rb
@@ -41,11 +41,11 @@ describe "knife deps", :workstation do
file "cookbooks/soup/recipes/chicken.rb", ""
end
it "knife deps reports all dependencies" do
- knife("deps /roles/starring.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
+ knife("deps /roles/starring.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
EOM
end
end
@@ -60,11 +60,11 @@ EOM
file "cookbooks/soup/recipes/chicken.rb", ""
end
it "knife deps reports all dependencies" do
- knife("deps /roles/starring.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
+ knife("deps /roles/starring.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
EOM
end
end
@@ -94,11 +94,11 @@ EOM
file "nodes/mort.json", { "run_list" => %w{role[minor] recipe[quiche] recipe[soup::chicken]} }
end
it "knife deps reports just the node" do
- knife("deps /nodes/mort.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/nodes/mort.json
+ knife("deps /nodes/mort.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /nodes/mort.json
EOM
end
end
@@ -148,56 +148,56 @@ depends "kettle"'
end
it "knife deps reports all dependencies" do
- knife("deps /nodes/mort.json").should_succeed <<EOM
-/environments/desert.json
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps /nodes/mort.json").should_succeed <<~EOM
+ /environments/desert.json
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps * reports all dependencies of all things" do
- knife("deps /nodes/*").should_succeed <<EOM
-/roles/minor.json
-/nodes/bart.json
-/environments/desert.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps /nodes/*").should_succeed <<~EOM
+ /roles/minor.json
+ /nodes/bart.json
+ /environments/desert.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps a b reports all dependencies of a and b" do
- knife("deps /nodes/bart.json /nodes/mort.json").should_succeed <<EOM
-/roles/minor.json
-/nodes/bart.json
-/environments/desert.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps /nodes/bart.json /nodes/mort.json").should_succeed <<~EOM
+ /roles/minor.json
+ /nodes/bart.json
+ /environments/desert.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps --tree /* shows dependencies in a tree" do
- knife("deps --tree /nodes/*").should_succeed <<EOM
-/nodes/bart.json
- /roles/minor.json
-/nodes/mort.json
- /environments/desert.json
- /roles/starring.json
- /roles/minor.json
- /cookbooks/quiche
- /cookbooks/soup
+ knife("deps --tree /nodes/*").should_succeed <<~EOM
+ /nodes/bart.json
+ /roles/minor.json
+ /nodes/mort.json
+ /environments/desert.json
+ /roles/starring.json
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
EOM
end
it "knife deps --tree --no-recurse shows only the first level of dependencies" do
- knife("deps --tree --no-recurse /nodes/*").should_succeed <<EOM
-/nodes/bart.json
- /roles/minor.json
-/nodes/mort.json
- /environments/desert.json
- /roles/starring.json
+ knife("deps --tree --no-recurse /nodes/*").should_succeed <<~EOM
+ /nodes/bart.json
+ /roles/minor.json
+ /nodes/mort.json
+ /environments/desert.json
+ /roles/starring.json
EOM
end
end
@@ -232,17 +232,17 @@ depends "foo"'
file "roles/self.json", { "run_list" => [ "role[self]" ] }
end
it "knife deps prints each once" do
- knife("deps /roles/foo.json /roles/self.json").should_succeed <<EOM
-/roles/baz.json
-/roles/bar.json
-/roles/foo.json
-/roles/self.json
+ knife("deps /roles/foo.json /roles/self.json").should_succeed <<~EOM
+ /roles/baz.json
+ /roles/bar.json
+ /roles/foo.json
+ /roles/self.json
EOM
end
it "knife deps --tree prints each once" do
knife("deps --tree /roles/foo.json /roles/self.json") do
expect(stdout).to eq("/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n")
- expect(stderr).to eq("WARNING: No knife configuration file found\n")
+ expect(stderr).to eq("WARNING: No knife configuration file found. See https://docs.chef.io/config_rb_knife.html for details.\n")
end
end
end
@@ -252,44 +252,44 @@ EOM
when_the_repository "is empty" do
it "knife deps /blah reports an error" do
knife("deps /blah").should_fail(
- :exit_code => 2,
- :stdout => "/blah\n",
- :stderr => "ERROR: /blah: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/blah\n",
+ stderr: "ERROR: /blah: No such file or directory\n"
)
end
it "knife deps /roles/x.json reports an error" do
knife("deps /roles/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/roles/x.json\n",
- :stderr => "ERROR: /roles/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/roles/x.json\n",
+ stderr: "ERROR: /roles/x.json: No such file or directory\n"
)
end
it "knife deps /nodes/x.json reports an error" do
knife("deps /nodes/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/nodes/x.json\n",
- :stderr => "ERROR: /nodes/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/nodes/x.json\n",
+ stderr: "ERROR: /nodes/x.json: No such file or directory\n"
)
end
it "knife deps /environments/x.json reports an error" do
knife("deps /environments/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/environments/x.json\n",
- :stderr => "ERROR: /environments/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/environments/x.json\n",
+ stderr: "ERROR: /environments/x.json: No such file or directory\n"
)
end
it "knife deps /cookbooks/x reports an error" do
knife("deps /cookbooks/x").should_fail(
- :exit_code => 2,
- :stdout => "/cookbooks/x\n",
- :stderr => "ERROR: /cookbooks/x: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/cookbooks/x\n",
+ stderr: "ERROR: /cookbooks/x: No such file or directory\n"
)
end
it "knife deps /data_bags/bag/item.json reports an error" do
knife("deps /data_bags/bag/item.json").should_fail(
- :exit_code => 2,
- :stdout => "/data_bags/bag/item.json\n",
- :stderr => "ERROR: /data_bags/bag/item.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/data_bags/bag/item.json\n",
+ stderr: "ERROR: /data_bags/bag/item.json: No such file or directory\n"
)
end
end
@@ -299,9 +299,9 @@ EOM
end
it "knife deps reports the cookbook, along with an error" do
knife("deps /roles/starring.json").should_fail(
- :exit_code => 2,
- :stdout => "/cookbooks/quiche\n/roles/starring.json\n",
- :stderr => "ERROR: /cookbooks/quiche: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/cookbooks/quiche\n/roles/starring.json\n",
+ stderr: "ERROR: /cookbooks/quiche: No such file or directory\n"
)
end
end
@@ -311,9 +311,9 @@ EOM
end
it "knife deps reports the environment, along with an error" do
knife("deps /nodes/mort.json").should_fail(
- :exit_code => 2,
- :stdout => "/environments/desert.json\n/nodes/mort.json\n",
- :stderr => "ERROR: /environments/desert.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/environments/desert.json\n/nodes/mort.json\n",
+ stderr: "ERROR: /environments/desert.json: No such file or directory\n"
)
end
end
@@ -323,9 +323,9 @@ EOM
end
it "knife deps reports the role, along with an error" do
knife("deps /roles/starring.json").should_fail(
- :exit_code => 2,
- :stdout => "/roles/minor.json\n/roles/starring.json\n",
- :stderr => "ERROR: /roles/minor.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/roles/minor.json\n/roles/starring.json\n",
+ stderr: "ERROR: /roles/minor.json: No such file or directory\n"
)
end
end
@@ -337,9 +337,9 @@ EOM
end
it "knife deps /roles reports an error" do
knife("deps /roles").should_fail(
- :exit_code => 2,
- :stderr => "ERROR: /roles: No such file or directory\n",
- :stdout => "/roles\n"
+ exit_code: 2,
+ stderr: "ERROR: /roles: No such file or directory\n",
+ stdout: "/roles\n"
)
end
end
@@ -378,11 +378,11 @@ EOM
cookbook "soup", "1.0.0", { "metadata.rb" => %Q{name "soup"\nversion "1.0.0"\n}, "recipes" => { "chicken.rb" => "" } }
end
it "knife deps reports all dependencies" do
- knife("deps --remote /roles/starring.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
+ knife("deps --remote /roles/starring.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
EOM
end
end
@@ -395,11 +395,11 @@ EOM
cookbook "soup", "1.0.0", { "metadata.rb" => %Q{name "soup"\nversion "1.0.0"\n}, "recipes" => { "chicken.rb" => "" } }
end
it "knife deps reports all dependencies" do
- knife("deps --remote /roles/starring.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
+ knife("deps --remote /roles/starring.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
EOM
end
end
@@ -427,11 +427,11 @@ EOM
node "mort", { "run_list" => %w{role[minor] recipe[quiche] recipe[soup::chicken]} }
end
it "knife deps reports just the node" do
- knife("deps --remote /nodes/mort.json").should_succeed <<EOM
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/nodes/mort.json
+ knife("deps --remote /nodes/mort.json").should_succeed <<~EOM
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /nodes/mort.json
EOM
end
end
@@ -477,56 +477,56 @@ depends "kettle"', "recipes" => { "default.rb" => "" } }
end
it "knife deps reports all dependencies" do
- knife("deps --remote /nodes/mort.json").should_succeed <<EOM
-/environments/desert.json
-/roles/minor.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps --remote /nodes/mort.json").should_succeed <<~EOM
+ /environments/desert.json
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps * reports all dependencies of all things" do
- knife("deps --remote /nodes/*").should_succeed <<EOM
-/roles/minor.json
-/nodes/bart.json
-/environments/desert.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps --remote /nodes/*").should_succeed <<~EOM
+ /roles/minor.json
+ /nodes/bart.json
+ /environments/desert.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps a b reports all dependencies of a and b" do
- knife("deps --remote /nodes/bart.json /nodes/mort.json").should_succeed <<EOM
-/roles/minor.json
-/nodes/bart.json
-/environments/desert.json
-/cookbooks/quiche
-/cookbooks/soup
-/roles/starring.json
-/nodes/mort.json
+ knife("deps --remote /nodes/bart.json /nodes/mort.json").should_succeed <<~EOM
+ /roles/minor.json
+ /nodes/bart.json
+ /environments/desert.json
+ /cookbooks/quiche
+ /cookbooks/soup
+ /roles/starring.json
+ /nodes/mort.json
EOM
end
it "knife deps --tree /* shows dependencies in a tree" do
- knife("deps --remote --tree /nodes/*").should_succeed <<EOM
-/nodes/bart.json
- /roles/minor.json
-/nodes/mort.json
- /environments/desert.json
- /roles/starring.json
- /roles/minor.json
- /cookbooks/quiche
- /cookbooks/soup
+ knife("deps --remote --tree /nodes/*").should_succeed <<~EOM
+ /nodes/bart.json
+ /roles/minor.json
+ /nodes/mort.json
+ /environments/desert.json
+ /roles/starring.json
+ /roles/minor.json
+ /cookbooks/quiche
+ /cookbooks/soup
EOM
end
it "knife deps --tree --no-recurse shows only the first level of dependencies" do
- knife("deps --remote --tree --no-recurse /nodes/*").should_succeed <<EOM
-/nodes/bart.json
- /roles/minor.json
-/nodes/mort.json
- /environments/desert.json
- /roles/starring.json
+ knife("deps --remote --tree --no-recurse /nodes/*").should_succeed <<~EOM
+ /nodes/bart.json
+ /roles/minor.json
+ /nodes/mort.json
+ /environments/desert.json
+ /roles/starring.json
EOM
end
end
@@ -544,21 +544,21 @@ depends "foo"' }
depends "self"' }
end
it "knife deps prints each once" do
- knife("deps --remote /cookbooks/foo /cookbooks/self").should_succeed <<EOM
-/cookbooks/baz
-/cookbooks/bar
-/cookbooks/foo
-/cookbooks/self
+ knife("deps --remote /cookbooks/foo /cookbooks/self").should_succeed <<~EOM
+ /cookbooks/baz
+ /cookbooks/bar
+ /cookbooks/foo
+ /cookbooks/self
EOM
end
it "knife deps --tree prints each once" do
- knife("deps --remote --tree /cookbooks/foo /cookbooks/self").should_succeed <<EOM
-/cookbooks/foo
- /cookbooks/bar
- /cookbooks/baz
- /cookbooks/foo
-/cookbooks/self
- /cookbooks/self
+ knife("deps --remote --tree /cookbooks/foo /cookbooks/self").should_succeed <<~EOM
+ /cookbooks/foo
+ /cookbooks/bar
+ /cookbooks/baz
+ /cookbooks/foo
+ /cookbooks/self
+ /cookbooks/self
EOM
end
end
@@ -570,17 +570,17 @@ EOM
role "self", { "run_list" => [ "role[self]" ] }
end
it "knife deps prints each once" do
- knife("deps --remote /roles/foo.json /roles/self.json").should_succeed <<EOM
-/roles/baz.json
-/roles/bar.json
-/roles/foo.json
-/roles/self.json
+ knife("deps --remote /roles/foo.json /roles/self.json").should_succeed <<~EOM
+ /roles/baz.json
+ /roles/bar.json
+ /roles/foo.json
+ /roles/self.json
EOM
end
it "knife deps --tree prints each once" do
knife("deps --remote --tree /roles/foo.json /roles/self.json") do
expect(stdout).to eq("/roles/foo.json\n /roles/bar.json\n /roles/baz.json\n /roles/foo.json\n/roles/self.json\n /roles/self.json\n")
- expect(stderr).to eq("WARNING: No knife configuration file found\n")
+ expect(stderr).to eq("WARNING: No knife configuration file found. See https://docs.chef.io/config_rb_knife.html for details.\n")
end
end
end
@@ -590,44 +590,44 @@ EOM
when_the_chef_server "is empty" do
it "knife deps /blah reports an error" do
knife("deps --remote /blah").should_fail(
- :exit_code => 2,
- :stdout => "/blah\n",
- :stderr => "ERROR: /blah: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/blah\n",
+ stderr: "ERROR: /blah: No such file or directory\n"
)
end
it "knife deps /roles/x.json reports an error" do
knife("deps --remote /roles/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/roles/x.json\n",
- :stderr => "ERROR: /roles/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/roles/x.json\n",
+ stderr: "ERROR: /roles/x.json: No such file or directory\n"
)
end
it "knife deps /nodes/x.json reports an error" do
knife("deps --remote /nodes/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/nodes/x.json\n",
- :stderr => "ERROR: /nodes/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/nodes/x.json\n",
+ stderr: "ERROR: /nodes/x.json: No such file or directory\n"
)
end
it "knife deps /environments/x.json reports an error" do
knife("deps --remote /environments/x.json").should_fail(
- :exit_code => 2,
- :stdout => "/environments/x.json\n",
- :stderr => "ERROR: /environments/x.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/environments/x.json\n",
+ stderr: "ERROR: /environments/x.json: No such file or directory\n"
)
end
it "knife deps /cookbooks/x reports an error" do
knife("deps --remote /cookbooks/x").should_fail(
- :exit_code => 2,
- :stdout => "/cookbooks/x\n",
- :stderr => "ERROR: /cookbooks/x: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/cookbooks/x\n",
+ stderr: "ERROR: /cookbooks/x: No such file or directory\n"
)
end
it "knife deps /data_bags/bag/item reports an error" do
knife("deps --remote /data_bags/bag/item.json").should_fail(
- :exit_code => 2,
- :stdout => "/data_bags/bag/item.json\n",
- :stderr => "ERROR: /data_bags/bag/item.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/data_bags/bag/item.json\n",
+ stderr: "ERROR: /data_bags/bag/item.json: No such file or directory\n"
)
end
end
@@ -637,9 +637,9 @@ EOM
end
it "knife deps reports the cookbook, along with an error" do
knife("deps --remote /roles/starring.json").should_fail(
- :exit_code => 2,
- :stdout => "/cookbooks/quiche\n/roles/starring.json\n",
- :stderr => "ERROR: /cookbooks/quiche: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/cookbooks/quiche\n/roles/starring.json\n",
+ stderr: "ERROR: /cookbooks/quiche: No such file or directory\n"
)
end
end
@@ -649,9 +649,9 @@ EOM
end
it "knife deps reports the environment, along with an error" do
knife("deps --remote /nodes/mort.json").should_fail(
- :exit_code => 2,
- :stdout => "/environments/desert.json\n/nodes/mort.json\n",
- :stderr => "ERROR: /environments/desert.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/environments/desert.json\n/nodes/mort.json\n",
+ stderr: "ERROR: /environments/desert.json: No such file or directory\n"
)
end
end
@@ -661,9 +661,9 @@ EOM
end
it "knife deps reports the role, along with an error" do
knife("deps --remote /roles/starring.json").should_fail(
- :exit_code => 2,
- :stdout => "/roles/minor.json\n/roles/starring.json\n",
- :stderr => "ERROR: /roles/minor.json: No such file or directory\n"
+ exit_code: 2,
+ stdout: "/roles/minor.json\n/roles/starring.json\n",
+ stderr: "ERROR: /roles/minor.json: No such file or directory\n"
)
end
end
diff --git a/spec/integration/knife/diff_spec.rb b/spec/integration/knife/diff_spec.rb
index b3bd23f48e..9e54558300 100644
--- a/spec/integration/knife/diff_spec.rb
+++ b/spec/integration/knife/diff_spec.rb
@@ -46,18 +46,18 @@ describe "knife diff", :workstation do
end
it "knife diff reports everything as deleted" do
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients/chef-validator.json
-D\t/clients/chef-webui.json
-D\t/clients/x.json
-D\t/cookbooks/x
-D\t/data_bags/x
-D\t/environments/_default.json
-D\t/environments/x.json
-D\t/nodes/x.json
-D\t/roles/x.json
-D\t/users/admin.json
-D\t/users/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients/chef-validator.json
+ D\t/clients/chef-webui.json
+ D\t/clients/x.json
+ D\t/cookbooks/x
+ D\t/data_bags/x
+ D\t/environments/_default.json
+ D\t/environments/x.json
+ D\t/nodes/x.json
+ D\t/roles/x.json
+ D\t/users/admin.json
+ D\t/users/x.json
EOM
end
end
@@ -92,16 +92,16 @@ EOM
context "except the role file" do
before do
- file "roles/x.json", <<EOM
-{
- "foo": "bar"
-}
+ file "roles/x.json", <<~EOM
+ {
+ "foo": "bar"
+ }
EOM
end
it "knife diff reports the role as different" do
- knife("diff --name-status /").should_succeed <<EOM
-M\t/roles/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ M\t/roles/x.json
EOM
end
end
@@ -120,31 +120,31 @@ EOM
end
it "knife diff reports the new files as added" do
- knife("diff --name-status /").should_succeed <<EOM
-A\t/clients/y.json
-A\t/cookbooks/x/blah.rb
-A\t/cookbooks/y
-A\t/data_bags/x/z.json
-A\t/data_bags/y
-A\t/environments/y.json
-A\t/nodes/y.json
-A\t/roles/y.json
-A\t/users/y.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ A\t/clients/y.json
+ A\t/cookbooks/x/blah.rb
+ A\t/cookbooks/y
+ A\t/data_bags/x/z.json
+ A\t/data_bags/y
+ A\t/environments/y.json
+ A\t/nodes/y.json
+ A\t/roles/y.json
+ A\t/users/y.json
EOM
end
context "when cwd is the data_bags directory" do
before { cwd "data_bags" }
it "knife diff reports different data bags" do
- knife("diff --name-status").should_succeed <<EOM
-A\tx/z.json
-A\ty
+ knife("diff --name-status").should_succeed <<~EOM
+ A\tx/z.json
+ A\ty
EOM
end
it "knife diff * reports different data bags" do
- knife("diff --name-status *").should_succeed <<EOM
-A\tx/z.json
-A\ty
+ knife("diff --name-status *").should_succeed <<~EOM
+ A\tx/z.json
+ A\ty
EOM
end
end
@@ -153,14 +153,14 @@ EOM
when_the_repository "is empty" do
it "knife diff reports everything as deleted" do
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
end
@@ -179,17 +179,17 @@ EOM
end
it "knife diff /cookbooks/x shows differences" do
- knife("diff --name-status /cookbooks/x").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks/x").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
it "knife diff --diff-filter=MAT does not show deleted files" do
- knife("diff --diff-filter=MAT --name-status /cookbooks/x").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --diff-filter=MAT --name-status /cookbooks/x").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
end
@@ -210,10 +210,10 @@ EOM
end
it "knife diff /cookbooks/x shows the differences" do
- knife("diff --name-status /cookbooks/x").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks/x").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
end
@@ -224,10 +224,10 @@ EOM
end
it "knife diff /cookbooks/x shows the differences" do
- knife("diff --name-status /cookbooks/x").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin0.9.9.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks/x").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin0.9.9.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
end
@@ -247,7 +247,7 @@ EOM
end
when_the_chef_server "has an environment with a different value" do
before { environment "x", { "description" => "hi" } }
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
- "name": "x",
@@ -277,7 +277,7 @@ EOM
environment "x", {}
end
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
- "name": "x"
@@ -291,7 +291,7 @@ EOM
before do
environment "x", { "description" => "lo" }
end
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
"name": "x",
@@ -311,7 +311,7 @@ EOM
it "knife diff reports an error and does a textual diff" do
error_text = "WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF"
error_match = Regexp.new(Regexp.escape(error_text))
- knife("diff /environments/x.json").should_succeed(/- "name": "x"/, :stderr => error_match)
+ knife("diff /environments/x.json").should_succeed(/- "name": "x"/, stderr: error_match)
end
end
end
@@ -341,18 +341,18 @@ EOM
end
it "knife diff reports everything as deleted" do
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients/chef-validator.json
-D\t/clients/chef-webui.json
-D\t/clients/x.json
-D\t/cookbooks/x-1.0.0
-D\t/data_bags/x
-D\t/environments/_default.json
-D\t/environments/x.json
-D\t/nodes/x.json
-D\t/roles/x.json
-D\t/users/admin.json
-D\t/users/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients/chef-validator.json
+ D\t/clients/chef-webui.json
+ D\t/clients/x.json
+ D\t/cookbooks/x-1.0.0
+ D\t/data_bags/x
+ D\t/environments/_default.json
+ D\t/environments/x.json
+ D\t/nodes/x.json
+ D\t/roles/x.json
+ D\t/users/admin.json
+ D\t/users/x.json
EOM
end
end
@@ -386,16 +386,16 @@ EOM
context "except the role file" do
before do
- file "roles/x.json", <<EOM
-{
- "foo": "bar"
-}
+ file "roles/x.json", <<~EOM
+ {
+ "foo": "bar"
+ }
EOM
end
it "knife diff reports the role as different" do
- knife("diff --name-status /").should_succeed <<EOM
-M\t/roles/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ M\t/roles/x.json
EOM
end
end
@@ -415,32 +415,32 @@ EOM
end
it "knife diff reports the new files as added" do
- knife("diff --name-status /").should_succeed <<EOM
-A\t/clients/y.json
-A\t/cookbooks/x-1.0.0/blah.rb
-A\t/cookbooks/x-2.0.0
-A\t/cookbooks/y-1.0.0
-A\t/data_bags/x/z.json
-A\t/data_bags/y
-A\t/environments/y.json
-A\t/nodes/y.json
-A\t/roles/y.json
-A\t/users/y.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ A\t/clients/y.json
+ A\t/cookbooks/x-1.0.0/blah.rb
+ A\t/cookbooks/x-2.0.0
+ A\t/cookbooks/y-1.0.0
+ A\t/data_bags/x/z.json
+ A\t/data_bags/y
+ A\t/environments/y.json
+ A\t/nodes/y.json
+ A\t/roles/y.json
+ A\t/users/y.json
EOM
end
context "when cwd is the data_bags directory" do
before { cwd "data_bags" }
it "knife diff reports different data bags" do
- knife("diff --name-status").should_succeed <<EOM
-A\tx/z.json
-A\ty
+ knife("diff --name-status").should_succeed <<~EOM
+ A\tx/z.json
+ A\ty
EOM
end
it "knife diff * reports different data bags" do
- knife("diff --name-status *").should_succeed <<EOM
-A\tx/z.json
-A\ty
+ knife("diff --name-status *").should_succeed <<~EOM
+ A\tx/z.json
+ A\ty
EOM
end
end
@@ -449,14 +449,14 @@ EOM
when_the_repository "is empty" do
it "knife diff reports everything as deleted" do
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
end
@@ -475,8 +475,8 @@ EOM
end
it "knife diff /cookbooks shows differences" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x-1.0.1
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x-1.0.1
EOM
end
@@ -501,9 +501,9 @@ EOM
end
it "knife diff /cookbooks shows the differences" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x-1.0.1
-A\t/cookbooks/x-1.0.0
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x-1.0.1
+ A\t/cookbooks/x-1.0.0
EOM
end
end
@@ -514,9 +514,9 @@ EOM
end
it "knife diff /cookbooks shows the differences" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x-0.9.9
-A\t/cookbooks/x-1.0.0
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x-0.9.9
+ A\t/cookbooks/x-1.0.0
EOM
end
end
@@ -533,7 +533,7 @@ EOM
end
when_the_chef_server "has an environment with a different value" do
before { environment "x", { "description" => "hi" } }
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
- "name": "x",
@@ -560,7 +560,7 @@ EOM
end
when_the_chef_server "has an environment with no value" do
before { environment "x", {} }
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
- "name": "x"
@@ -574,7 +574,7 @@ EOM
before do
environment "x", { "description" => "lo" }
end
- it "knife diff reports the difference", :skip => (RUBY_VERSION < "1.9") do
+ it "knife diff reports the difference", skip: (RUBY_VERSION < "1.9") do
knife("diff /environments/x.json").should_succeed(/
{
"name": "x",
@@ -594,7 +594,7 @@ EOM
it "knife diff reports an error and does a textual diff" do
error_text = "WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF"
error_match = Regexp.new(Regexp.escape(error_text))
- knife("diff /environments/x.json").should_succeed(/- "name": "x"/, :stderr => error_match)
+ knife("diff /environments/x.json").should_succeed(/- "name": "x"/, stderr: error_match)
end
end
end
diff --git a/spec/integration/knife/download_spec.rb b/spec/integration/knife/download_spec.rb
index be0fc9d708..04610ba4e7 100644
--- a/spec/integration/knife/download_spec.rb
+++ b/spec/integration/knife/download_spec.rb
@@ -48,20 +48,20 @@ describe "knife download", :workstation do
end
it "knife download downloads everything" do
- knife("download /").should_succeed <<EOM
-Created /clients/chef-validator.json
-Created /clients/chef-webui.json
-Created /clients/x.json
-Created /cookbooks/x
-Created /cookbooks/x/metadata.rb
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments/_default.json
-Created /environments/x.json
-Created /nodes/x.json
-Created /roles/x.json
-Created /users/admin.json
-Created /users/x.json
+ knife("download /").should_succeed <<~EOM
+ Created /clients/chef-validator.json
+ Created /clients/chef-webui.json
+ Created /clients/x.json
+ Created /cookbooks/x
+ Created /cookbooks/x/metadata.rb
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments/_default.json
+ Created /environments/x.json
+ Created /nodes/x.json
+ Created /roles/x.json
+ Created /users/admin.json
+ Created /users/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -94,22 +94,22 @@ EOM
context "except the role file" do
before do
- file "roles/x.json", <<EOM
-{
- "chef_type": "role",
- "default_attributes": {
- },
- "description": "blarghle",
- "env_run_lists": {
- },
- "json_class": "Chef::Role",
- "name": "x",
- "override_attributes": {
- },
- "run_list": [
-
- ]
-}
+ file "roles/x.json", <<~EOM
+ {
+ "chef_type": "role",
+ "default_attributes": {
+ },
+ "description": "blarghle",
+ "env_run_lists": {
+ },
+ "json_class": "Chef::Role",
+ "name": "x",
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -126,22 +126,22 @@ EOM
context "except the role file is textually different, but not ACTUALLY different" do
before do
- file "roles/x.json", <<EOM
-{
- "chef_type": "role",
- "default_attributes": {
- },
- "env_run_lists": {
- },
- "json_class": "Chef::Role",
- "name": "x",
- "description": "",
- "override_attributes": {
- },
- "run_list": [
-
- ]
-}
+ file "roles/x.json", <<~EOM
+ {
+ "chef_type": "role",
+ "default_attributes": {
+ },
+ "env_run_lists": {
+ },
+ "json_class": "Chef::Role",
+ "name": "x",
+ "description": "",
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -166,30 +166,30 @@ EOM
it "knife download does nothing" do
knife("download /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-A\t/clients/y.json
-A\t/cookbooks/x/blah.rb
-A\t/cookbooks/y
-A\t/data_bags/x/z.json
-A\t/data_bags/y
-A\t/environments/y.json
-A\t/nodes/y.json
-A\t/roles/y.json
-A\t/users/y.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ A\t/clients/y.json
+ A\t/cookbooks/x/blah.rb
+ A\t/cookbooks/y
+ A\t/data_bags/x/z.json
+ A\t/data_bags/y
+ A\t/environments/y.json
+ A\t/nodes/y.json
+ A\t/roles/y.json
+ A\t/users/y.json
EOM
end
it "knife download --purge deletes the extra files" do
- knife("download --purge /").should_succeed <<EOM
-Deleted extra entry /clients/y.json (purge is on)
-Deleted extra entry /cookbooks/x/blah.rb (purge is on)
-Deleted extra entry /cookbooks/y (purge is on)
-Deleted extra entry /data_bags/x/z.json (purge is on)
-Deleted extra entry /data_bags/y (purge is on)
-Deleted extra entry /environments/y.json (purge is on)
-Deleted extra entry /nodes/y.json (purge is on)
-Deleted extra entry /roles/y.json (purge is on)
-Deleted extra entry /users/y.json (purge is on)
+ knife("download --purge /").should_succeed <<~EOM
+ Deleted extra entry /clients/y.json (purge is on)
+ Deleted extra entry /cookbooks/x/blah.rb (purge is on)
+ Deleted extra entry /cookbooks/y (purge is on)
+ Deleted extra entry /data_bags/x/z.json (purge is on)
+ Deleted extra entry /data_bags/y (purge is on)
+ Deleted extra entry /environments/y.json (purge is on)
+ Deleted extra entry /nodes/y.json (purge is on)
+ Deleted extra entry /roles/y.json (purge is on)
+ Deleted extra entry /users/y.json (purge is on)
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -198,53 +198,53 @@ EOM
when_the_repository "is empty" do
it "knife download creates the extra files" do
- knife("download /").should_succeed <<EOM
-Created /clients
-Created /clients/chef-validator.json
-Created /clients/chef-webui.json
-Created /clients/x.json
-Created /cookbooks
-Created /cookbooks/x
-Created /cookbooks/x/metadata.rb
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments
-Created /environments/_default.json
-Created /environments/x.json
-Created /nodes
-Created /nodes/x.json
-Created /roles
-Created /roles/x.json
-Created /users
-Created /users/admin.json
-Created /users/x.json
+ knife("download /").should_succeed <<~EOM
+ Created /clients
+ Created /clients/chef-validator.json
+ Created /clients/chef-webui.json
+ Created /clients/x.json
+ Created /cookbooks
+ Created /cookbooks/x
+ Created /cookbooks/x/metadata.rb
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments
+ Created /environments/_default.json
+ Created /environments/x.json
+ Created /nodes
+ Created /nodes/x.json
+ Created /roles
+ Created /roles/x.json
+ Created /users
+ Created /users/admin.json
+ Created /users/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
it "knife download --no-diff creates the extra files" do
- knife("download --no-diff /").should_succeed <<EOM
-Created /clients
-Created /clients/chef-validator.json
-Created /clients/chef-webui.json
-Created /clients/x.json
-Created /cookbooks
-Created /cookbooks/x
-Created /cookbooks/x/metadata.rb
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments
-Created /environments/_default.json
-Created /environments/x.json
-Created /nodes
-Created /nodes/x.json
-Created /roles
-Created /roles/x.json
-Created /users
-Created /users/admin.json
-Created /users/x.json
+ knife("download --no-diff /").should_succeed <<~EOM
+ Created /clients
+ Created /clients/chef-validator.json
+ Created /clients/chef-webui.json
+ Created /clients/x.json
+ Created /cookbooks
+ Created /cookbooks/x
+ Created /cookbooks/x/metadata.rb
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments
+ Created /environments/_default.json
+ Created /environments/x.json
+ Created /nodes
+ Created /nodes/x.json
+ Created /roles
+ Created /roles/x.json
+ Created /users
+ Created /users/admin.json
+ Created /users/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -255,7 +255,7 @@ EOM
end
it "knife download with no parameters reports an error" do
- knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", :stdout => /USAGE/
+ knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", stdout: /USAGE/
end
end
end
@@ -269,22 +269,22 @@ EOM
end
it "knife download of one data bag item itself succeeds" do
- knife("download /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("download /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/z.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/z.json
EOM
end
it "knife download /data_bags/x /data_bags/x/y.json downloads x once" do
- knife("download /data_bags/x /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /data_bags/x/z.json
+ knife("download /data_bags/x /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /data_bags/x/z.json
EOM
end
end
@@ -292,20 +292,20 @@ EOM
when_the_repository "has three data bag items" do
before do
- file "data_bags/x/deleted.json", <<EOM
-{
- "id": "deleted"
-}
+ file "data_bags/x/deleted.json", <<~EOM
+ {
+ "id": "deleted"
+ }
EOM
- file "data_bags/x/modified.json", <<EOM
-{
- "id": "modified"
-}
+ file "data_bags/x/modified.json", <<~EOM
+ {
+ "id": "modified"
+ }
EOM
- file "data_bags/x/unmodified.json", <<EOM
-{
- "id": "unmodified"
-}
+ file "data_bags/x/unmodified.json", <<~EOM
+ {
+ "id": "unmodified"
+ }
EOM
end
@@ -319,62 +319,62 @@ EOM
end
it "knife download of the modified file succeeds" do
- knife("download /data_bags/x/modified.json").should_succeed <<EOM
-Updated /data_bags/x/modified.json
+ knife("download /data_bags/x/modified.json").should_succeed <<~EOM
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the unmodified file does nothing" do
knife("download /data_bags/x/unmodified.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the added file succeeds" do
- knife("download /data_bags/x/added.json").should_succeed <<EOM
-Created /data_bags/x/added.json
+ knife("download /data_bags/x/added.json").should_succeed <<~EOM
+ Created /data_bags/x/added.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the deleted file does nothing" do
knife("download /data_bags/x/deleted.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download --purge of the deleted file deletes it" do
- knife("download --purge /data_bags/x/deleted.json").should_succeed <<EOM
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("download --purge /data_bags/x/deleted.json").should_succeed <<~EOM
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
EOM
end
it "knife download of the entire data bag downloads everything" do
- knife("download /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
+ knife("download /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download --purge of the entire data bag downloads everything" do
- knife("download --purge /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("download --purge /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -383,21 +383,21 @@ EOM
cwd "data_bags"
end
it "knife download fails" do
- knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", :stdout => /USAGE/
+ knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", stdout: /USAGE/
end
it "knife download --purge . downloads everything" do
- knife("download --purge .").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("download --purge .").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
it "knife download --purge * downloads everything" do
- knife("download --purge *").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("download --purge *").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -418,47 +418,47 @@ EOM
it "knife download of a modified file succeeds" do
knife("download /cookbooks/x/metadata.rb").should_succeed "Updated /cookbooks/x/metadata.rb\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x/y.rb
-A\t/cookbooks/x/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x/y.rb
+ A\t/cookbooks/x/z.rb
EOM
end
it "knife download of a deleted file does nothing" do
knife("download /cookbooks/x/z.rb").should_succeed ""
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/y.rb
-A\t/cookbooks/x/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/y.rb
+ A\t/cookbooks/x/z.rb
EOM
end
it "knife download --purge of a deleted file succeeds" do
knife("download --purge /cookbooks/x/z.rb").should_succeed "Deleted extra entry /cookbooks/x/z.rb (purge is on)\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/y.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/y.rb
EOM
end
it "knife download of an added file succeeds" do
knife("download /cookbooks/x/y.rb").should_succeed "Created /cookbooks/x/y.rb\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-A\t/cookbooks/x/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ A\t/cookbooks/x/z.rb
EOM
end
it "knife download of the cookbook itself succeeds" do
- knife("download /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/metadata.rb
-Created /cookbooks/x/y.rb
+ knife("download /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/metadata.rb
+ Created /cookbooks/x/y.rb
EOM
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-A\t/cookbooks/x/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ A\t/cookbooks/x/z.rb
EOM
end
it "knife download --purge of the cookbook itself succeeds" do
- knife("download --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/metadata.rb
-Created /cookbooks/x/y.rb
-Deleted extra entry /cookbooks/x/z.rb (purge is on)
+ knife("download --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/metadata.rb
+ Created /cookbooks/x/y.rb
+ Deleted extra entry /cookbooks/x/z.rb (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -478,10 +478,10 @@ EOM
end
it "knife download /cookbooks/x downloads the latest version" do
- knife("download --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/metadata.rb
-Created /cookbooks/x/onlyin1.0.1.rb
-Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
+ knife("download --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/metadata.rb
+ Created /cookbooks/x/onlyin1.0.1.rb
+ Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -494,8 +494,8 @@ EOM
end
it "knife download /cookbooks/x downloads the updated file" do
- knife("download --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/onlyin1.0.0.rb
+ knife("download --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/onlyin1.0.0.rb
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -507,10 +507,10 @@ EOM
end
it "knife download /cookbooks/x downloads the latest version" do
- knife("download --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/metadata.rb
-Created /cookbooks/x/onlyin1.0.1.rb
-Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
+ knife("download --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/metadata.rb
+ Created /cookbooks/x/onlyin1.0.1.rb
+ Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -522,10 +522,10 @@ EOM
end
it "knife download /cookbooks/x downloads the old version" do
- knife("download --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x/metadata.rb
-Created /cookbooks/x/onlyin0.9.9.rb
-Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
+ knife("download --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x/metadata.rb
+ Created /cookbooks/x/onlyin0.9.9.rb
+ Deleted extra entry /cookbooks/x/onlyin1.0.0.rb (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -538,14 +538,14 @@ EOM
end
when_the_repository "has the role in ruby" do
before do
- file "roles/x.rb", <<EOM
-name "x"
-description "x"
+ file "roles/x.rb", <<~EOM
+ name "x"
+ description "x"
EOM
end
it "knife download refuses to change the role" do
- knife("download /roles/x.json").should_succeed "", :stderr => "WARNING: /roles/x.rb cannot be updated (can't safely update ruby files).\n"
+ knife("download /roles/x.json").should_succeed "", stderr: "WARNING: /roles/x.rb cannot be updated (can't safely update ruby files).\n"
knife("diff --name-status /roles/x.json").should_succeed "M\t/roles/x.rb\n"
end
end
@@ -560,13 +560,13 @@ EOM
file "environments/x.json", "{"
end
it "knife download succeeds" do
- warning = <<-EOH
-WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
- {
- (right here) ------^
+ warning = <<~EOH
+ WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ {
+ (right here) ------^
EOH
- knife("download /environments/x.json").should_succeed "Updated /environments/x.json\n", :stderr => warning
+ knife("download /environments/x.json").should_succeed "Updated /environments/x.json\n", stderr: warning
knife("diff --name-status /environments/x.json").should_succeed ""
end
end
@@ -617,20 +617,20 @@ EOH
end
it "knife download downloads everything" do
- knife("download /").should_succeed <<EOM
-Created /clients/chef-validator.json
-Created /clients/chef-webui.json
-Created /clients/x.json
-Created /cookbooks/x-1.0.0
-Created /cookbooks/x-1.0.0/metadata.rb
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments/_default.json
-Created /environments/x.json
-Created /nodes/x.json
-Created /roles/x.json
-Created /users/admin.json
-Created /users/x.json
+ knife("download /").should_succeed <<~EOM
+ Created /clients/chef-validator.json
+ Created /clients/chef-webui.json
+ Created /clients/x.json
+ Created /cookbooks/x-1.0.0
+ Created /cookbooks/x-1.0.0/metadata.rb
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments/_default.json
+ Created /environments/x.json
+ Created /nodes/x.json
+ Created /roles/x.json
+ Created /users/admin.json
+ Created /users/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -674,22 +674,22 @@ EOM
context "except the role file is textually different, but not ACTUALLY different" do
before do
- file "roles/x.json", <<EOM
-{
- "chef_type": "role" ,
- "default_attributes": {
- },
- "env_run_lists": {
- },
- "json_class": "Chef::Role",
- "name": "x",
- "description": "",
- "override_attributes": {
- },
- "run_list": [
-
- ]
-}
+ file "roles/x.json", <<~EOM
+ {
+ "chef_type": "role" ,
+ "default_attributes": {
+ },
+ "env_run_lists": {
+ },
+ "json_class": "Chef::Role",
+ "name": "x",
+ "description": "",
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -715,32 +715,32 @@ EOM
it "knife download does nothing" do
knife("download /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-A\t/clients/y.json
-A\t/cookbooks/x-1.0.0/blah.rb
-A\t/cookbooks/x-2.0.0
-A\t/cookbooks/y-1.0.0
-A\t/data_bags/x/z.json
-A\t/data_bags/y
-A\t/environments/y.json
-A\t/nodes/y.json
-A\t/roles/y.json
-A\t/users/y.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ A\t/clients/y.json
+ A\t/cookbooks/x-1.0.0/blah.rb
+ A\t/cookbooks/x-2.0.0
+ A\t/cookbooks/y-1.0.0
+ A\t/data_bags/x/z.json
+ A\t/data_bags/y
+ A\t/environments/y.json
+ A\t/nodes/y.json
+ A\t/roles/y.json
+ A\t/users/y.json
EOM
end
it "knife download --purge deletes the extra files" do
- knife("download --purge /").should_succeed <<EOM
-Deleted extra entry /clients/y.json (purge is on)
-Deleted extra entry /cookbooks/x-1.0.0/blah.rb (purge is on)
-Deleted extra entry /cookbooks/x-2.0.0 (purge is on)
-Deleted extra entry /cookbooks/y-1.0.0 (purge is on)
-Deleted extra entry /data_bags/x/z.json (purge is on)
-Deleted extra entry /data_bags/y (purge is on)
-Deleted extra entry /environments/y.json (purge is on)
-Deleted extra entry /nodes/y.json (purge is on)
-Deleted extra entry /roles/y.json (purge is on)
-Deleted extra entry /users/y.json (purge is on)
+ knife("download --purge /").should_succeed <<~EOM
+ Deleted extra entry /clients/y.json (purge is on)
+ Deleted extra entry /cookbooks/x-1.0.0/blah.rb (purge is on)
+ Deleted extra entry /cookbooks/x-2.0.0 (purge is on)
+ Deleted extra entry /cookbooks/y-1.0.0 (purge is on)
+ Deleted extra entry /data_bags/x/z.json (purge is on)
+ Deleted extra entry /data_bags/y (purge is on)
+ Deleted extra entry /environments/y.json (purge is on)
+ Deleted extra entry /nodes/y.json (purge is on)
+ Deleted extra entry /roles/y.json (purge is on)
+ Deleted extra entry /users/y.json (purge is on)
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -749,27 +749,27 @@ EOM
when_the_repository "is empty" do
it "knife download creates the extra files" do
- knife("download /").should_succeed <<EOM
-Created /clients
-Created /clients/chef-validator.json
-Created /clients/chef-webui.json
-Created /clients/x.json
-Created /cookbooks
-Created /cookbooks/x-1.0.0
-Created /cookbooks/x-1.0.0/metadata.rb
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments
-Created /environments/_default.json
-Created /environments/x.json
-Created /nodes
-Created /nodes/x.json
-Created /roles
-Created /roles/x.json
-Created /users
-Created /users/admin.json
-Created /users/x.json
+ knife("download /").should_succeed <<~EOM
+ Created /clients
+ Created /clients/chef-validator.json
+ Created /clients/chef-webui.json
+ Created /clients/x.json
+ Created /cookbooks
+ Created /cookbooks/x-1.0.0
+ Created /cookbooks/x-1.0.0/metadata.rb
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments
+ Created /environments/_default.json
+ Created /environments/x.json
+ Created /nodes
+ Created /nodes/x.json
+ Created /roles
+ Created /roles/x.json
+ Created /users
+ Created /users/admin.json
+ Created /users/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -779,7 +779,7 @@ EOM
cwd "."
end
it "knife download with no parameters reports an error" do
- knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", :stdout => /USAGE/
+ knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", stdout: /USAGE/
end
end
end
@@ -793,13 +793,13 @@ EOM
end
it "knife download of one data bag item itself succeeds" do
- knife("download /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("download /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/z.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/z.json
EOM
end
end
@@ -807,20 +807,20 @@ EOM
when_the_repository "has three data bag items" do
before do
- file "data_bags/x/deleted.json", <<EOM
-{
- "id": "deleted"
-}
+ file "data_bags/x/deleted.json", <<~EOM
+ {
+ "id": "deleted"
+ }
EOM
- file "data_bags/x/modified.json", <<EOM
-{
- "id": "modified"
-}
+ file "data_bags/x/modified.json", <<~EOM
+ {
+ "id": "modified"
+ }
EOM
- file "data_bags/x/unmodified.json", <<EOM
-{
- "id": "unmodified"
-}
+ file "data_bags/x/unmodified.json", <<~EOM
+ {
+ "id": "unmodified"
+ }
EOM
end
@@ -834,62 +834,62 @@ EOM
end
it "knife download of the modified file succeeds" do
- knife("download /data_bags/x/modified.json").should_succeed <<EOM
-Updated /data_bags/x/modified.json
+ knife("download /data_bags/x/modified.json").should_succeed <<~EOM
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the unmodified file does nothing" do
knife("download /data_bags/x/unmodified.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the added file succeeds" do
- knife("download /data_bags/x/added.json").should_succeed <<EOM
-Created /data_bags/x/added.json
+ knife("download /data_bags/x/added.json").should_succeed <<~EOM
+ Created /data_bags/x/added.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download of the deleted file does nothing" do
knife("download /data_bags/x/deleted.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download --purge of the deleted file deletes it" do
- knife("download --purge /data_bags/x/deleted.json").should_succeed <<EOM
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("download --purge /data_bags/x/deleted.json").should_succeed <<~EOM
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/added.json
-M\t/data_bags/x/modified.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/added.json
+ M\t/data_bags/x/modified.json
EOM
end
it "knife download of the entire data bag downloads everything" do
- knife("download /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
+ knife("download /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-A\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ A\t/data_bags/x/deleted.json
EOM
end
it "knife download --purge of the entire data bag downloads everything" do
- knife("download --purge /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("download --purge /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -898,21 +898,21 @@ EOM
cwd "data_bags"
end
it "knife download fails" do
- knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", :stdout => /USAGE/
+ knife("download").should_fail "FATAL: You must specify at least one argument. If you want to download everything in this directory, run \"knife download .\"\n", stdout: /USAGE/
end
it "knife download --purge . downloads everything" do
- knife("download --purge .").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("download --purge .").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
it "knife download --purge * downloads everything" do
- knife("download --purge *").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("download --purge *").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -933,47 +933,47 @@ EOM
it "knife download of a modified file succeeds" do
knife("download /cookbooks/x-1.0.0/metadata.rb").should_succeed "Updated /cookbooks/x-1.0.0/metadata.rb\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x-1.0.0/y.rb
-A\t/cookbooks/x-1.0.0/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x-1.0.0/y.rb
+ A\t/cookbooks/x-1.0.0/z.rb
EOM
end
it "knife download of a deleted file does nothing" do
knife("download /cookbooks/x-1.0.0/z.rb").should_succeed ""
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x-1.0.0/metadata.rb
-D\t/cookbooks/x-1.0.0/y.rb
-A\t/cookbooks/x-1.0.0/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x-1.0.0/metadata.rb
+ D\t/cookbooks/x-1.0.0/y.rb
+ A\t/cookbooks/x-1.0.0/z.rb
EOM
end
it "knife download --purge of a deleted file succeeds" do
knife("download --purge /cookbooks/x-1.0.0/z.rb").should_succeed "Deleted extra entry /cookbooks/x-1.0.0/z.rb (purge is on)\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x-1.0.0/metadata.rb
-D\t/cookbooks/x-1.0.0/y.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x-1.0.0/metadata.rb
+ D\t/cookbooks/x-1.0.0/y.rb
EOM
end
it "knife download of an added file succeeds" do
knife("download /cookbooks/x-1.0.0/y.rb").should_succeed "Created /cookbooks/x-1.0.0/y.rb\n"
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x-1.0.0/metadata.rb
-A\t/cookbooks/x-1.0.0/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x-1.0.0/metadata.rb
+ A\t/cookbooks/x-1.0.0/z.rb
EOM
end
it "knife download of the cookbook itself succeeds" do
- knife("download /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0/metadata.rb
-Created /cookbooks/x-1.0.0/y.rb
+ knife("download /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0/metadata.rb
+ Created /cookbooks/x-1.0.0/y.rb
EOM
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-A\t/cookbooks/x-1.0.0/z.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ A\t/cookbooks/x-1.0.0/z.rb
EOM
end
it "knife download --purge of the cookbook itself succeeds" do
- knife("download --purge /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0/metadata.rb
-Created /cookbooks/x-1.0.0/y.rb
-Deleted extra entry /cookbooks/x-1.0.0/z.rb (purge is on)
+ knife("download --purge /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0/metadata.rb
+ Created /cookbooks/x-1.0.0/y.rb
+ Deleted extra entry /cookbooks/x-1.0.0/z.rb (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -993,11 +993,11 @@ EOM
end
it "knife download /cookbooks/x downloads the latest version" do
- knife("download --purge /cookbooks").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0/onlyin1.0.0.rb
-Created /cookbooks/x-1.0.1
-Created /cookbooks/x-1.0.1/metadata.rb
-Created /cookbooks/x-1.0.1/onlyin1.0.1.rb
+ knife("download --purge /cookbooks").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0/onlyin1.0.0.rb
+ Created /cookbooks/x-1.0.1
+ Created /cookbooks/x-1.0.1/metadata.rb
+ Created /cookbooks/x-1.0.1/onlyin1.0.1.rb
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1010,11 +1010,11 @@ EOM
end
it "knife download /cookbooks downloads the updated file" do
- knife("download --purge /cookbooks").should_succeed <<EOM
-Created /cookbooks/x-0.9.9
-Created /cookbooks/x-0.9.9/metadata.rb
-Created /cookbooks/x-0.9.9/onlyin0.9.9.rb
-Updated /cookbooks/x-1.0.0/onlyin1.0.0.rb
+ knife("download --purge /cookbooks").should_succeed <<~EOM
+ Created /cookbooks/x-0.9.9
+ Created /cookbooks/x-0.9.9/metadata.rb
+ Created /cookbooks/x-0.9.9/onlyin0.9.9.rb
+ Updated /cookbooks/x-1.0.0/onlyin1.0.0.rb
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1026,11 +1026,11 @@ EOM
end
it "knife download /cookbooks/x downloads the latest version" do
- knife("download --purge /cookbooks").should_succeed <<EOM
-Created /cookbooks/x-1.0.1
-Created /cookbooks/x-1.0.1/metadata.rb
-Created /cookbooks/x-1.0.1/onlyin1.0.1.rb
-Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
+ knife("download --purge /cookbooks").should_succeed <<~EOM
+ Created /cookbooks/x-1.0.1
+ Created /cookbooks/x-1.0.1/metadata.rb
+ Created /cookbooks/x-1.0.1/onlyin1.0.1.rb
+ Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1042,11 +1042,11 @@ EOM
end
it "knife download --purge /cookbooks downloads the old version and deletes the new version" do
- knife("download --purge /cookbooks").should_succeed <<EOM
-Created /cookbooks/x-0.9.9
-Created /cookbooks/x-0.9.9/metadata.rb
-Created /cookbooks/x-0.9.9/onlyin0.9.9.rb
-Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
+ knife("download --purge /cookbooks").should_succeed <<~EOM
+ Created /cookbooks/x-0.9.9
+ Created /cookbooks/x-0.9.9/metadata.rb
+ Created /cookbooks/x-0.9.9/onlyin0.9.9.rb
+ Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1102,16 +1102,16 @@ EOM
new_result
}.at_least(:once)
- knife("download /cookbooks/x").should_succeed <<EOM
-Created /cookbooks
-Created /cookbooks/x
-Created /cookbooks/x/metadata.rb
+ knife("download /cookbooks/x").should_succeed <<~EOM
+ Created /cookbooks
+ Created /cookbooks/x
+ Created /cookbooks/x/metadata.rb
EOM
end
end
end
- when_the_chef_server "is in Enterprise mode", :osc_compat => false, :single_org => false do
+ when_the_chef_server "is in Enterprise mode", osc_compat: false, single_org: false do
before do
user "foo", {}
user "bar", {}
@@ -1125,70 +1125,70 @@ EOM
when_the_repository "has all the default stuff" do
before do
- knife("download /").should_succeed <<EOM
-Created /acls
-Created /acls/clients
-Created /acls/clients/foo-validator.json
-Created /acls/containers
-Created /acls/containers/clients.json
-Created /acls/containers/containers.json
-Created /acls/containers/cookbook_artifacts.json
-Created /acls/containers/cookbooks.json
-Created /acls/containers/data.json
-Created /acls/containers/environments.json
-Created /acls/containers/groups.json
-Created /acls/containers/nodes.json
-Created /acls/containers/policies.json
-Created /acls/containers/policy_groups.json
-Created /acls/containers/roles.json
-Created /acls/containers/sandboxes.json
-Created /acls/cookbook_artifacts
-Created /acls/cookbooks
-Created /acls/data_bags
-Created /acls/environments
-Created /acls/environments/_default.json
-Created /acls/groups
-Created /acls/groups/admins.json
-Created /acls/groups/billing-admins.json
-Created /acls/groups/clients.json
-Created /acls/groups/users.json
-Created /acls/nodes
-Created /acls/policies
-Created /acls/policy_groups
-Created /acls/roles
-Created /acls/organization.json
-Created /clients
-Created /clients/foo-validator.json
-Created /containers
-Created /containers/clients.json
-Created /containers/containers.json
-Created /containers/cookbook_artifacts.json
-Created /containers/cookbooks.json
-Created /containers/data.json
-Created /containers/environments.json
-Created /containers/groups.json
-Created /containers/nodes.json
-Created /containers/policies.json
-Created /containers/policy_groups.json
-Created /containers/roles.json
-Created /containers/sandboxes.json
-Created /cookbook_artifacts
-Created /cookbooks
-Created /data_bags
-Created /environments
-Created /environments/_default.json
-Created /groups
-Created /groups/admins.json
-Created /groups/billing-admins.json
-Created /groups/clients.json
-Created /groups/users.json
-Created /invitations.json
-Created /members.json
-Created /nodes
-Created /org.json
-Created /policies
-Created /policy_groups
-Created /roles
+ knife("download /").should_succeed <<~EOM
+ Created /acls
+ Created /acls/clients
+ Created /acls/clients/foo-validator.json
+ Created /acls/containers
+ Created /acls/containers/clients.json
+ Created /acls/containers/containers.json
+ Created /acls/containers/cookbook_artifacts.json
+ Created /acls/containers/cookbooks.json
+ Created /acls/containers/data.json
+ Created /acls/containers/environments.json
+ Created /acls/containers/groups.json
+ Created /acls/containers/nodes.json
+ Created /acls/containers/policies.json
+ Created /acls/containers/policy_groups.json
+ Created /acls/containers/roles.json
+ Created /acls/containers/sandboxes.json
+ Created /acls/cookbook_artifacts
+ Created /acls/cookbooks
+ Created /acls/data_bags
+ Created /acls/environments
+ Created /acls/environments/_default.json
+ Created /acls/groups
+ Created /acls/groups/admins.json
+ Created /acls/groups/billing-admins.json
+ Created /acls/groups/clients.json
+ Created /acls/groups/users.json
+ Created /acls/nodes
+ Created /acls/policies
+ Created /acls/policy_groups
+ Created /acls/roles
+ Created /acls/organization.json
+ Created /clients
+ Created /clients/foo-validator.json
+ Created /containers
+ Created /containers/clients.json
+ Created /containers/containers.json
+ Created /containers/cookbook_artifacts.json
+ Created /containers/cookbooks.json
+ Created /containers/data.json
+ Created /containers/environments.json
+ Created /containers/groups.json
+ Created /containers/nodes.json
+ Created /containers/policies.json
+ Created /containers/policy_groups.json
+ Created /containers/roles.json
+ Created /containers/sandboxes.json
+ Created /cookbook_artifacts
+ Created /cookbooks
+ Created /data_bags
+ Created /environments
+ Created /environments/_default.json
+ Created /groups
+ Created /groups/admins.json
+ Created /groups/billing-admins.json
+ Created /groups/clients.json
+ Created /groups/users.json
+ Created /invitations.json
+ Created /members.json
+ Created /nodes
+ Created /org.json
+ Created /policies
+ Created /policy_groups
+ Created /roles
EOM
end
@@ -1217,43 +1217,43 @@ EOM
end
before do
- knife("download /acls /groups/clients.json /groups/users.json").should_succeed <<-EOM
-Created /acls/clients/x.json
-Created /acls/containers/x.json
-Created /acls/cookbook_artifacts/x.json
-Created /acls/cookbooks/x.json
-Created /acls/data_bags/x.json
-Created /acls/environments/x.json
-Created /acls/groups/x.json
-Created /acls/nodes/x.json
-Created /acls/policies/blah.json
-Created /acls/policies/x.json
-Created /acls/policy_groups/x.json
-Created /acls/roles/x.json
-Updated /groups/clients.json
-Updated /groups/users.json
+ knife("download /acls /groups/clients.json /groups/users.json").should_succeed <<~EOM
+ Created /acls/clients/x.json
+ Created /acls/containers/x.json
+ Created /acls/cookbook_artifacts/x.json
+ Created /acls/cookbooks/x.json
+ Created /acls/data_bags/x.json
+ Created /acls/environments/x.json
+ Created /acls/groups/x.json
+ Created /acls/nodes/x.json
+ Created /acls/policies/blah.json
+ Created /acls/policies/x.json
+ Created /acls/policy_groups/x.json
+ Created /acls/roles/x.json
+ Updated /groups/clients.json
+ Updated /groups/users.json
EOM
end
it "knife download / downloads everything" do
- knife("download /").should_succeed <<EOM
-Created /clients/x.json
-Created /containers/x.json
-Created /cookbook_artifacts/x-1x1
-Created /cookbook_artifacts/x-1x1/metadata.rb
-Created /cookbooks/x
-Created /cookbooks/x/metadata.rb
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments/x.json
-Created /groups/x.json
-Updated /invitations.json
-Updated /members.json
-Created /nodes/x.json
-Created /policies/blah-1.0.0.json
-Created /policies/x-1.0.0.json
-Created /policy_groups/x.json
-Created /roles/x.json
+ knife("download /").should_succeed <<~EOM
+ Created /clients/x.json
+ Created /containers/x.json
+ Created /cookbook_artifacts/x-1x1
+ Created /cookbook_artifacts/x-1x1/metadata.rb
+ Created /cookbooks/x
+ Created /cookbooks/x/metadata.rb
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments/x.json
+ Created /groups/x.json
+ Updated /invitations.json
+ Updated /members.json
+ Created /nodes/x.json
+ Created /policies/blah-1.0.0.json
+ Created /policies/x-1.0.0.json
+ Created /policy_groups/x.json
+ Created /roles/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -1308,21 +1308,21 @@ EOM
end
it "knife download updates everything" do
- knife("download /").should_succeed <<EOM
-Updated /clients/x.json
-Updated /cookbook_artifacts/x-1x1/metadata.rb
-Updated /cookbooks/x/metadata.rb
-Updated /data_bags/x/y.json
-Updated /environments/x.json
-Updated /groups/x.json
-Updated /invitations.json
-Updated /members.json
-Updated /nodes/x.json
-Updated /org.json
-Created /policies/blah-1.0.0.json
-Updated /policies/x-1.0.0.json
-Updated /policy_groups/x.json
-Updated /roles/x.json
+ knife("download /").should_succeed <<~EOM
+ Updated /clients/x.json
+ Updated /cookbook_artifacts/x-1x1/metadata.rb
+ Updated /cookbooks/x/metadata.rb
+ Updated /data_bags/x/y.json
+ Updated /environments/x.json
+ Updated /groups/x.json
+ Updated /invitations.json
+ Updated /members.json
+ Updated /nodes/x.json
+ Updated /org.json
+ Created /policies/blah-1.0.0.json
+ Updated /policies/x-1.0.0.json
+ Updated /policy_groups/x.json
+ Updated /roles/x.json
EOM
knife("diff --name-status /").should_succeed ""
end
diff --git a/spec/integration/knife/environment_compare_spec.rb b/spec/integration/knife/environment_compare_spec.rb
index 720bead8c0..d3999fffa3 100644
--- a/spec/integration/knife/environment_compare_spec.rb
+++ b/spec/integration/knife/environment_compare_spec.rb
@@ -44,29 +44,29 @@ describe "knife environment compare", :workstation do
# rubocop:disable Layout/TrailingWhitespace
it "displays the cookbooks for a single environment" do
- knife("environment compare x").should_succeed <<EOM
- x
-blah = 1.0.0
-krad >= 1.0.0
-
+ knife("environment compare x").should_succeed <<~EOM
+ x
+ blah = 1.0.0
+ krad >= 1.0.0
+
EOM
end
it "compares the cookbooks for two environments" do
- knife("environment compare x y").should_succeed <<EOM
- x y
-blah = 1.0.0 = 1.1.0
-krad >= 1.0.0 >= 1.0.0
-
+ knife("environment compare x y").should_succeed <<~EOM
+ x y
+ blah = 1.0.0 = 1.1.0
+ krad >= 1.0.0 >= 1.0.0
+
EOM
end
it "compares the cookbooks for all environments" do
- knife("environment compare --all").should_succeed <<EOM
- x y
-blah = 1.0.0 = 1.1.0
-krad >= 1.0.0 >= 1.0.0
-
+ knife("environment compare --all").should_succeed <<~EOM
+ x y
+ blah = 1.0.0 = 1.1.0
+ krad >= 1.0.0 >= 1.0.0
+
EOM
end
# rubocop:enable Layout/TrailingWhitespace
diff --git a/spec/integration/knife/environment_from_file_spec.rb b/spec/integration/knife/environment_from_file_spec.rb
index 67d4373939..8948a3772c 100644
--- a/spec/integration/knife/environment_from_file_spec.rb
+++ b/spec/integration/knife/environment_from_file_spec.rb
@@ -29,84 +29,84 @@ describe "knife environment from file", :workstation do
when_the_repository "has some environments" do
before do
- file "environments/cons.json", <<EOM
-{
- "name": "cons",
- "description": "An environment",
- "cookbook_versions": {
-
- },
- "json_class": "Chef::Environment",
- "chef_type": "environment",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
-
- }
-}
+ file "environments/cons.json", <<~EOM
+ {
+ "name": "cons",
+ "description": "An environment",
+ "cookbook_versions": {
+
+ },
+ "json_class": "Chef::Environment",
+ "chef_type": "environment",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
+
+ }
+ }
EOM
- file "environments/car.json", <<EOM
-{
- "name": "car",
- "description": "An environment for list nodes",
- "cookbook_versions": {
-
- },
- "json_class": "Chef::Environment",
- "chef_type": "environment",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
-
- }
-}
+ file "environments/car.json", <<~EOM
+ {
+ "name": "car",
+ "description": "An environment for list nodes",
+ "cookbook_versions": {
+
+ },
+ "json_class": "Chef::Environment",
+ "chef_type": "environment",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
+
+ }
+ }
EOM
- file "environments/cdr.json", <<EOM
-{
- "name": "cdr",
- "description": "An environment for last nodes",
- "cookbook_versions": {
-
- },
- "json_class": "Chef::Environment",
- "chef_type": "environment",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
-
- }
-}
+ file "environments/cdr.json", <<~EOM
+ {
+ "name": "cdr",
+ "description": "An environment for last nodes",
+ "cookbook_versions": {
+
+ },
+ "json_class": "Chef::Environment",
+ "chef_type": "environment",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
+
+ }
+ }
EOM
end
it "uploads a single file" do
- knife("environment from file #{env_dir}/cons.json").should_succeed stderr: <<EOM
-Updated Environment cons
+ knife("environment from file #{env_dir}/cons.json").should_succeed stderr: <<~EOM
+ Updated Environment cons
EOM
end
it "uploads many files" do
- knife("environment from file #{env_dir}/cons.json #{env_dir}/car.json #{env_dir}/cdr.json").should_succeed stderr: <<EOM
-Updated Environment cons
-Updated Environment car
-Updated Environment cdr
+ knife("environment from file #{env_dir}/cons.json #{env_dir}/car.json #{env_dir}/cdr.json").should_succeed stderr: <<~EOM
+ Updated Environment cons
+ Updated Environment car
+ Updated Environment cdr
EOM
end
it "uploads all environments in the repository" do
cwd(".")
knife("environment from file --all")
- knife("environment list").should_succeed <<EOM
-_default
-car
-cdr
-cons
+ knife("environment list").should_succeed <<~EOM
+ _default
+ car
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/environment_list_spec.rb b/spec/integration/knife/environment_list_spec.rb
index 5e74453d1f..0ac2df6300 100644
--- a/spec/integration/knife/environment_list_spec.rb
+++ b/spec/integration/knife/environment_list_spec.rb
@@ -30,10 +30,10 @@ describe "knife environment list", :workstation do
end
it "lists all the environments" do
- knife("environment list").should_succeed <<EOM
-_default
-b
-y
+ knife("environment list").should_succeed <<~EOM
+ _default
+ b
+ y
EOM
end
diff --git a/spec/integration/knife/environment_show_spec.rb b/spec/integration/knife/environment_show_spec.rb
index dabdfac6a2..fdf41e70ce 100644
--- a/spec/integration/knife/environment_show_spec.rb
+++ b/spec/integration/knife/environment_show_spec.rb
@@ -32,44 +32,44 @@ describe "knife environment show", :workstation do
# rubocop:disable Layout/TrailingWhitespace
it "shows an environment" do
- knife("environment show b").should_succeed <<EOM
-chef_type: environment
-cookbook_versions:
-default_attributes:
- baz:
- raz.my: mataz
- foo: bar
-description:
-json_class: Chef::Environment
-name: b
-override_attributes:
+ knife("environment show b").should_succeed <<~EOM
+ chef_type: environment
+ cookbook_versions:
+ default_attributes:
+ baz:
+ raz.my: mataz
+ foo: bar
+ description:
+ json_class: Chef::Environment
+ name: b
+ override_attributes:
EOM
end
# rubocop:enable Layout/TrailingWhitespace
it "shows the requested attribute of an environment" do
- knife("environment show b -a default_attributes").should_succeed <<EOM
-b:
- default_attributes:
- baz:
- raz.my: mataz
- foo: bar
+ knife("environment show b -a default_attributes").should_succeed <<~EOM
+ b:
+ default_attributes:
+ baz:
+ raz.my: mataz
+ foo: bar
EOM
end
it "shows the requested nested attribute of an environment" do
- knife("environment show b -a default_attributes.baz").should_succeed <<EON
-b:
- default_attributes.baz:
- raz.my: mataz
+ knife("environment show b -a default_attributes.baz").should_succeed <<~EON
+ b:
+ default_attributes.baz:
+ raz.my: mataz
EON
end
it "shows the requested attribute of an environment with custom field separator" do
- knife("environment show b -S: -a default_attributes:baz").should_succeed <<EOT
-b:
- default_attributes:baz:
- raz.my: mataz
+ knife("environment show b -S: -a default_attributes:baz").should_succeed <<~EOT
+ b:
+ default_attributes:baz:
+ raz.my: mataz
EOT
end
end
diff --git a/spec/integration/knife/list_spec.rb b/spec/integration/knife/list_spec.rb
index 4aa74f3f0e..39a3f77fc5 100644
--- a/spec/integration/knife/list_spec.rb
+++ b/spec/integration/knife/list_spec.rb
@@ -27,45 +27,45 @@ describe "knife list", :workstation do
when_the_chef_server "is empty" do
it "knife list / returns all top level directories" do
- knife("list /").should_succeed <<-EOM
-/clients
-/cookbooks
-/data_bags
-/environments
-/nodes
-/roles
-/users
+ knife("list /").should_succeed <<~EOM
+ /clients
+ /cookbooks
+ /data_bags
+ /environments
+ /nodes
+ /roles
+ /users
EOM
end
it "knife list -R / returns everything" do
- knife("list -R /").should_succeed <<-EOM
-/:
-clients
-cookbooks
-data_bags
-environments
-nodes
-roles
-users
+ knife("list -R /").should_succeed <<~EOM
+ /:
+ clients
+ cookbooks
+ data_bags
+ environments
+ nodes
+ roles
+ users
-/clients:
-chef-validator.json
-chef-webui.json
+ /clients:
+ chef-validator.json
+ chef-webui.json
-/cookbooks:
+ /cookbooks:
-/data_bags:
+ /data_bags:
-/environments:
-_default.json
+ /environments:
+ _default.json
-/nodes:
+ /nodes:
-/roles:
+ /roles:
-/users:
-admin.json
+ /users:
+ admin.json
EOM
end
end
@@ -92,160 +92,160 @@ EOM
end
it "knife list / returns all top level directories" do
- knife("list /").should_succeed <<-EOM
-/clients
-/cookbooks
-/data_bags
-/environments
-/nodes
-/roles
-/users
+ knife("list /").should_succeed <<~EOM
+ /clients
+ /cookbooks
+ /data_bags
+ /environments
+ /nodes
+ /roles
+ /users
EOM
end
it "knife list -R / returns everything" do
- knife("list -R /").should_succeed <<-EOM
-/:
-clients
-cookbooks
-data_bags
-environments
-nodes
-roles
-users
-
-/clients:
-chef-validator.json
-chef-webui.json
-client1.json
-client2.json
-
-/cookbooks:
-cookbook1
-cookbook2
-
-/cookbooks/cookbook1:
-metadata.rb
-
-/cookbooks/cookbook2:
-metadata.rb
-recipes
-
-/cookbooks/cookbook2/recipes:
-default.rb
-
-/data_bags:
-bag1
-bag2
-
-/data_bags/bag1:
-item1.json
-item2.json
-
-/data_bags/bag2:
-item1.json
-item2.json
-
-/environments:
-_default.json
-environment1.json
-environment2.json
-
-/nodes:
-node1.json
-node2.json
-
-/roles:
-role1.json
-role2.json
-
-/users:
-admin.json
-user1.json
-user2.json
+ knife("list -R /").should_succeed <<~EOM
+ /:
+ clients
+ cookbooks
+ data_bags
+ environments
+ nodes
+ roles
+ users
+
+ /clients:
+ chef-validator.json
+ chef-webui.json
+ client1.json
+ client2.json
+
+ /cookbooks:
+ cookbook1
+ cookbook2
+
+ /cookbooks/cookbook1:
+ metadata.rb
+
+ /cookbooks/cookbook2:
+ metadata.rb
+ recipes
+
+ /cookbooks/cookbook2/recipes:
+ default.rb
+
+ /data_bags:
+ bag1
+ bag2
+
+ /data_bags/bag1:
+ item1.json
+ item2.json
+
+ /data_bags/bag2:
+ item1.json
+ item2.json
+
+ /environments:
+ _default.json
+ environment1.json
+ environment2.json
+
+ /nodes:
+ node1.json
+ node2.json
+
+ /roles:
+ role1.json
+ role2.json
+
+ /users:
+ admin.json
+ user1.json
+ user2.json
EOM
end
it "knife list -R --flat / returns everything" do
- knife("list -R --flat /").should_succeed <<-EOM
-/clients
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/client1.json
-/clients/client2.json
-/cookbooks
-/cookbooks/cookbook1
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes
-/cookbooks/cookbook2/recipes/default.rb
-/data_bags
-/data_bags/bag1
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/nodes
-/nodes/node1.json
-/nodes/node2.json
-/roles
-/roles/role1.json
-/roles/role2.json
-/users
-/users/admin.json
-/users/user1.json
-/users/user2.json
+ knife("list -R --flat /").should_succeed <<~EOM
+ /clients
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/client1.json
+ /clients/client2.json
+ /cookbooks
+ /cookbooks/cookbook1
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes
+ /cookbooks/cookbook2/recipes/default.rb
+ /data_bags
+ /data_bags/bag1
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles
+ /roles/role1.json
+ /roles/role2.json
+ /users
+ /users/admin.json
+ /users/user1.json
+ /users/user2.json
EOM
end
it "knife list -Rfp / returns everything" do
- knife("list -Rfp /").should_succeed <<-EOM
-/clients/
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/client1.json
-/clients/client2.json
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes/
-/cookbooks/cookbook2/recipes/default.rb
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/nodes/
-/nodes/node1.json
-/nodes/node2.json
-/roles/
-/roles/role1.json
-/roles/role2.json
-/users/
-/users/admin.json
-/users/user1.json
-/users/user2.json
+ knife("list -Rfp /").should_succeed <<~EOM
+ /clients/
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/client1.json
+ /clients/client2.json
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes/
+ /cookbooks/cookbook2/recipes/default.rb
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes/
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles/
+ /roles/role1.json
+ /roles/role2.json
+ /users/
+ /users/admin.json
+ /users/user1.json
+ /users/user2.json
EOM
end
it "knife list /cookbooks returns the list of cookbooks" do
- knife("list /cookbooks").should_succeed <<-EOM
-/cookbooks/cookbook1
-/cookbooks/cookbook2
+ knife("list /cookbooks").should_succeed <<~EOM
+ /cookbooks/cookbook1
+ /cookbooks/cookbook2
EOM
end
@@ -254,50 +254,50 @@ EOM
end
it "knife list /**.rb returns all ruby files" do
- knife("list /**.rb").should_succeed <<-EOM
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes/default.rb
+ knife("list /**.rb").should_succeed <<~EOM
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes/default.rb
EOM
end
it "knife list /cookbooks/**.rb returns all ruby files" do
- knife("list /cookbooks/**.rb").should_succeed <<-EOM
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes/default.rb
+ knife("list /cookbooks/**.rb").should_succeed <<~EOM
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes/default.rb
EOM
end
it "knife list /**.json returns all json files" do
- knife("list /**.json").should_succeed <<-EOM
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/client1.json
-/clients/client2.json
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/nodes/node1.json
-/nodes/node2.json
-/roles/role1.json
-/roles/role2.json
-/users/admin.json
-/users/user1.json
-/users/user2.json
+ knife("list /**.json").should_succeed <<~EOM
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/client1.json
+ /clients/client2.json
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles/role1.json
+ /roles/role2.json
+ /users/admin.json
+ /users/user1.json
+ /users/user2.json
EOM
end
it "knife list /data**.json returns all data bag json files" do
- knife("list /data**.json").should_succeed <<-EOM
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
+ knife("list /data**.json").should_succeed <<~EOM
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
EOM
end
@@ -317,40 +317,40 @@ EOM
before { cwd "." }
it "knife list -Rfp returns everything" do
- knife("list -Rfp").should_succeed <<-EOM
-clients/
-clients/chef-validator.json
-clients/chef-webui.json
-clients/client1.json
-clients/client2.json
-cookbooks/
-cookbooks/cookbook1/
-cookbooks/cookbook1/metadata.rb
-cookbooks/cookbook2/
-cookbooks/cookbook2/metadata.rb
-cookbooks/cookbook2/recipes/
-cookbooks/cookbook2/recipes/default.rb
-data_bags/
-data_bags/bag1/
-data_bags/bag1/item1.json
-data_bags/bag1/item2.json
-data_bags/bag2/
-data_bags/bag2/item1.json
-data_bags/bag2/item2.json
-environments/
-environments/_default.json
-environments/environment1.json
-environments/environment2.json
-nodes/
-nodes/node1.json
-nodes/node2.json
-roles/
-roles/role1.json
-roles/role2.json
-users/
-users/admin.json
-users/user1.json
-users/user2.json
+ knife("list -Rfp").should_succeed <<~EOM
+ clients/
+ clients/chef-validator.json
+ clients/chef-webui.json
+ clients/client1.json
+ clients/client2.json
+ cookbooks/
+ cookbooks/cookbook1/
+ cookbooks/cookbook1/metadata.rb
+ cookbooks/cookbook2/
+ cookbooks/cookbook2/metadata.rb
+ cookbooks/cookbook2/recipes/
+ cookbooks/cookbook2/recipes/default.rb
+ data_bags/
+ data_bags/bag1/
+ data_bags/bag1/item1.json
+ data_bags/bag1/item2.json
+ data_bags/bag2/
+ data_bags/bag2/item1.json
+ data_bags/bag2/item2.json
+ environments/
+ environments/_default.json
+ environments/environment1.json
+ environments/environment2.json
+ nodes/
+ nodes/node1.json
+ nodes/node2.json
+ roles/
+ roles/role1.json
+ roles/role2.json
+ users/
+ users/admin.json
+ users/user1.json
+ users/user2.json
EOM
end
end
@@ -362,89 +362,89 @@ EOM
before { cwd "cookbooks" }
it "knife list -Rfp / returns everything" do
- knife("list -Rfp /").should_succeed <<-EOM
-/clients/
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/client1.json
-/clients/client2.json
-./
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/nodes/
-/nodes/node1.json
-/nodes/node2.json
-/roles/
-/roles/role1.json
-/roles/role2.json
-/users/
-/users/admin.json
-/users/user1.json
-/users/user2.json
+ knife("list -Rfp /").should_succeed <<~EOM
+ /clients/
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/client1.json
+ /clients/client2.json
+ ./
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes/
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles/
+ /roles/role1.json
+ /roles/role2.json
+ /users/
+ /users/admin.json
+ /users/user1.json
+ /users/user2.json
EOM
end
it "knife list -Rfp .. returns everything" do
- knife("list -Rfp ..").should_succeed <<-EOM
-/clients/
-/clients/chef-validator.json
-/clients/chef-webui.json
-/clients/client1.json
-/clients/client2.json
-./
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/nodes/
-/nodes/node1.json
-/nodes/node2.json
-/roles/
-/roles/role1.json
-/roles/role2.json
-/users/
-/users/admin.json
-/users/user1.json
-/users/user2.json
+ knife("list -Rfp ..").should_succeed <<~EOM
+ /clients/
+ /clients/chef-validator.json
+ /clients/chef-webui.json
+ /clients/client1.json
+ /clients/client2.json
+ ./
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes/
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles/
+ /roles/role1.json
+ /roles/role2.json
+ /users/
+ /users/admin.json
+ /users/user1.json
+ /users/user2.json
EOM
end
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
EOM
end
end
@@ -457,16 +457,16 @@ EOM
before { cwd "cookbooks/cookbook2" }
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-metadata.rb
-recipes/
-recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ metadata.rb
+ recipes/
+ recipes/default.rb
EOM
end
end
end
- when_the_repository "has a cookbooks directory and a symlinked cookbooks directory", :skip => (Chef::Platform.windows?) do
+ when_the_repository "has a cookbooks directory and a symlinked cookbooks directory", skip: (Chef::Platform.windows?) do
before do
directory "cookbooks"
symlink "symlinked", "cookbooks"
@@ -476,13 +476,13 @@ EOM
before { cwd "cookbooks" }
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
EOM
end
end
@@ -491,19 +491,19 @@ EOM
before { cwd "symlinked" }
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
EOM
end
end
end
- when_the_repository "has a real_cookbooks directory and a cookbooks symlink to it", :skip => (Chef::Platform.windows?) do
+ when_the_repository "has a real_cookbooks directory and a cookbooks symlink to it", skip: (Chef::Platform.windows?) do
before do
directory "real_cookbooks"
symlink "cookbooks", "real_cookbooks"
@@ -513,13 +513,13 @@ EOM
before { cwd "real_cookbooks" }
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
EOM
end
end
@@ -528,13 +528,13 @@ EOM
before { cwd "cookbooks" }
it "knife list -Rfp returns cookbooks" do
- knife("list -Rfp").should_succeed <<-EOM
-cookbook1/
-cookbook1/metadata.rb
-cookbook2/
-cookbook2/metadata.rb
-cookbook2/recipes/
-cookbook2/recipes/default.rb
+ knife("list -Rfp").should_succeed <<~EOM
+ cookbook1/
+ cookbook1/metadata.rb
+ cookbook2/
+ cookbook2/metadata.rb
+ cookbook2/recipes/
+ cookbook2/recipes/default.rb
EOM
end
end
@@ -589,36 +589,36 @@ EOM
end
it "knife list -Rfp / returns everything" do
- knife("list -Rp --local --flat /").should_succeed <<-EOM
-/clients/
-/clients/client1.json
-/clients/client2.json
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes/
-/cookbooks/cookbook2/recipes/default.rb
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/
-/environments/environment1.json
-/environments/environment2.json
-/nodes/
-/nodes/node1.json
-/nodes/node2.json
-/roles/
-/roles/role1.json
-/roles/role2.json
-/users/
-/users/user1.json
-/users/user2.json
+ knife("list -Rp --local --flat /").should_succeed <<~EOM
+ /clients/
+ /clients/client1.json
+ /clients/client2.json
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes/
+ /cookbooks/cookbook2/recipes/default.rb
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/
+ /environments/environment1.json
+ /environments/environment2.json
+ /nodes/
+ /nodes/node1.json
+ /nodes/node2.json
+ /roles/
+ /roles/role1.json
+ /roles/role2.json
+ /users/
+ /users/user1.json
+ /users/user2.json
EOM
end
@@ -638,7 +638,7 @@ EOM
end
end
- when_the_chef_server "is in Enterprise mode", :osc_compat => false, :single_org => false do
+ when_the_chef_server "is in Enterprise mode", osc_compat: false, single_org: false do
before do
organization "foo"
end
@@ -649,253 +649,253 @@ EOM
context "and is empty" do
it "knife list / returns all top level directories" do
- knife("list /").should_succeed <<-EOM
-/acls
-/clients
-/containers
-/cookbook_artifacts
-/cookbooks
-/data_bags
-/environments
-/groups
-/invitations.json
-/members.json
-/nodes
-/org.json
-/policies
-/policy_groups
-/roles
+ knife("list /").should_succeed <<~EOM
+ /acls
+ /clients
+ /containers
+ /cookbook_artifacts
+ /cookbooks
+ /data_bags
+ /environments
+ /groups
+ /invitations.json
+ /members.json
+ /nodes
+ /org.json
+ /policies
+ /policy_groups
+ /roles
EOM
end
it "knife list -R / returns everything" do
- knife("list -R /").should_succeed <<-EOM
-/:
-acls
-clients
-containers
-cookbook_artifacts
-cookbooks
-data_bags
-environments
-groups
-invitations.json
-members.json
-nodes
-org.json
-policies
-policy_groups
-roles
-
-/acls:
-clients
-containers
-cookbook_artifacts
-cookbooks
-data_bags
-environments
-groups
-nodes
-organization.json
-policies
-policy_groups
-roles
-
-/acls/clients:
-foo-validator.json
-
-/acls/containers:
-clients.json
-containers.json
-cookbook_artifacts.json
-cookbooks.json
-data.json
-environments.json
-groups.json
-nodes.json
-policies.json
-policy_groups.json
-roles.json
-sandboxes.json
-
-/acls/cookbook_artifacts:
-
-/acls/cookbooks:
-
-/acls/data_bags:
-
-/acls/environments:
-_default.json
-
-/acls/groups:
-admins.json
-billing-admins.json
-clients.json
-users.json
-
-/acls/nodes:
-
-/acls/policies:
-
-/acls/policy_groups:
-
-/acls/roles:
-
-/clients:
-foo-validator.json
-
-/containers:
-clients.json
-containers.json
-cookbook_artifacts.json
-cookbooks.json
-data.json
-environments.json
-groups.json
-nodes.json
-policies.json
-policy_groups.json
-roles.json
-sandboxes.json
-
-/cookbook_artifacts:
-
-/cookbooks:
-
-/data_bags:
-
-/environments:
-_default.json
-
-/groups:
-admins.json
-billing-admins.json
-clients.json
-users.json
-
-/nodes:
-
-/policies:
-
-/policy_groups:
-
-/roles:
+ knife("list -R /").should_succeed <<~EOM
+ /:
+ acls
+ clients
+ containers
+ cookbook_artifacts
+ cookbooks
+ data_bags
+ environments
+ groups
+ invitations.json
+ members.json
+ nodes
+ org.json
+ policies
+ policy_groups
+ roles
+
+ /acls:
+ clients
+ containers
+ cookbook_artifacts
+ cookbooks
+ data_bags
+ environments
+ groups
+ nodes
+ organization.json
+ policies
+ policy_groups
+ roles
+
+ /acls/clients:
+ foo-validator.json
+
+ /acls/containers:
+ clients.json
+ containers.json
+ cookbook_artifacts.json
+ cookbooks.json
+ data.json
+ environments.json
+ groups.json
+ nodes.json
+ policies.json
+ policy_groups.json
+ roles.json
+ sandboxes.json
+
+ /acls/cookbook_artifacts:
+
+ /acls/cookbooks:
+
+ /acls/data_bags:
+
+ /acls/environments:
+ _default.json
+
+ /acls/groups:
+ admins.json
+ billing-admins.json
+ clients.json
+ users.json
+
+ /acls/nodes:
+
+ /acls/policies:
+
+ /acls/policy_groups:
+
+ /acls/roles:
+
+ /clients:
+ foo-validator.json
+
+ /containers:
+ clients.json
+ containers.json
+ cookbook_artifacts.json
+ cookbooks.json
+ data.json
+ environments.json
+ groups.json
+ nodes.json
+ policies.json
+ policy_groups.json
+ roles.json
+ sandboxes.json
+
+ /cookbook_artifacts:
+
+ /cookbooks:
+
+ /data_bags:
+
+ /environments:
+ _default.json
+
+ /groups:
+ admins.json
+ billing-admins.json
+ clients.json
+ users.json
+
+ /nodes:
+
+ /policies:
+
+ /policy_groups:
+
+ /roles:
EOM
end
end
it "knife list -R / returns everything" do
- knife("list -R /").should_succeed <<-EOM
-/:
-acls
-clients
-containers
-cookbook_artifacts
-cookbooks
-data_bags
-environments
-groups
-invitations.json
-members.json
-nodes
-org.json
-policies
-policy_groups
-roles
-
-/acls:
-clients
-containers
-cookbook_artifacts
-cookbooks
-data_bags
-environments
-groups
-nodes
-organization.json
-policies
-policy_groups
-roles
-
-/acls/clients:
-foo-validator.json
-
-/acls/containers:
-clients.json
-containers.json
-cookbook_artifacts.json
-cookbooks.json
-data.json
-environments.json
-groups.json
-nodes.json
-policies.json
-policy_groups.json
-roles.json
-sandboxes.json
-
-/acls/cookbook_artifacts:
-
-/acls/cookbooks:
-
-/acls/data_bags:
-
-/acls/environments:
-_default.json
-
-/acls/groups:
-admins.json
-billing-admins.json
-clients.json
-users.json
-
-/acls/nodes:
-
-/acls/policies:
-
-/acls/policy_groups:
-
-/acls/roles:
-
-/clients:
-foo-validator.json
-
-/containers:
-clients.json
-containers.json
-cookbook_artifacts.json
-cookbooks.json
-data.json
-environments.json
-groups.json
-nodes.json
-policies.json
-policy_groups.json
-roles.json
-sandboxes.json
-
-/cookbook_artifacts:
-
-/cookbooks:
-
-/data_bags:
-
-/environments:
-_default.json
-
-/groups:
-admins.json
-billing-admins.json
-clients.json
-users.json
-
-/nodes:
-
-/policies:
-
-/policy_groups:
-
-/roles:
+ knife("list -R /").should_succeed <<~EOM
+ /:
+ acls
+ clients
+ containers
+ cookbook_artifacts
+ cookbooks
+ data_bags
+ environments
+ groups
+ invitations.json
+ members.json
+ nodes
+ org.json
+ policies
+ policy_groups
+ roles
+
+ /acls:
+ clients
+ containers
+ cookbook_artifacts
+ cookbooks
+ data_bags
+ environments
+ groups
+ nodes
+ organization.json
+ policies
+ policy_groups
+ roles
+
+ /acls/clients:
+ foo-validator.json
+
+ /acls/containers:
+ clients.json
+ containers.json
+ cookbook_artifacts.json
+ cookbooks.json
+ data.json
+ environments.json
+ groups.json
+ nodes.json
+ policies.json
+ policy_groups.json
+ roles.json
+ sandboxes.json
+
+ /acls/cookbook_artifacts:
+
+ /acls/cookbooks:
+
+ /acls/data_bags:
+
+ /acls/environments:
+ _default.json
+
+ /acls/groups:
+ admins.json
+ billing-admins.json
+ clients.json
+ users.json
+
+ /acls/nodes:
+
+ /acls/policies:
+
+ /acls/policy_groups:
+
+ /acls/roles:
+
+ /clients:
+ foo-validator.json
+
+ /containers:
+ clients.json
+ containers.json
+ cookbook_artifacts.json
+ cookbooks.json
+ data.json
+ environments.json
+ groups.json
+ nodes.json
+ policies.json
+ policy_groups.json
+ roles.json
+ sandboxes.json
+
+ /cookbook_artifacts:
+
+ /cookbooks:
+
+ /data_bags:
+
+ /environments:
+ _default.json
+
+ /groups:
+ admins.json
+ billing-admins.json
+ clients.json
+ users.json
+
+ /nodes:
+
+ /policies:
+
+ /policy_groups:
+
+ /roles:
EOM
end
@@ -931,127 +931,127 @@ EOM
end
it "knife list -Rfp / returns everything" do
- knife("list -Rfp /").should_succeed <<-EOM
-/acls/
-/acls/clients/
-/acls/clients/client1.json
-/acls/clients/client2.json
-/acls/clients/foo-validator.json
-/acls/containers/
-/acls/containers/clients.json
-/acls/containers/container1.json
-/acls/containers/container2.json
-/acls/containers/containers.json
-/acls/containers/cookbook_artifacts.json
-/acls/containers/cookbooks.json
-/acls/containers/data.json
-/acls/containers/environments.json
-/acls/containers/groups.json
-/acls/containers/nodes.json
-/acls/containers/policies.json
-/acls/containers/policy_groups.json
-/acls/containers/roles.json
-/acls/containers/sandboxes.json
-/acls/cookbook_artifacts/
-/acls/cookbook_artifacts/cookbook_artifact1.json
-/acls/cookbook_artifacts/cookbook_artifact2.json
-/acls/cookbooks/
-/acls/cookbooks/cookbook1.json
-/acls/cookbooks/cookbook2.json
-/acls/data_bags/
-/acls/data_bags/bag1.json
-/acls/data_bags/bag2.json
-/acls/environments/
-/acls/environments/_default.json
-/acls/environments/environment1.json
-/acls/environments/environment2.json
-/acls/groups/
-/acls/groups/admins.json
-/acls/groups/billing-admins.json
-/acls/groups/clients.json
-/acls/groups/group1.json
-/acls/groups/group2.json
-/acls/groups/users.json
-/acls/nodes/
-/acls/nodes/node1.json
-/acls/nodes/node2.json
-/acls/organization.json
-/acls/policies/
-/acls/policies/policy1.json
-/acls/policies/policy2.json
-/acls/policy_groups/
-/acls/policy_groups/policy_group1.json
-/acls/policy_groups/policy_group2.json
-/acls/roles/
-/acls/roles/role1.json
-/acls/roles/role2.json
-/clients/
-/clients/client1.json
-/clients/client2.json
-/clients/foo-validator.json
-/containers/
-/containers/clients.json
-/containers/container1.json
-/containers/container2.json
-/containers/containers.json
-/containers/cookbook_artifacts.json
-/containers/cookbooks.json
-/containers/data.json
-/containers/environments.json
-/containers/groups.json
-/containers/nodes.json
-/containers/policies.json
-/containers/policy_groups.json
-/containers/roles.json
-/containers/sandboxes.json
-/cookbook_artifacts/
-/cookbook_artifacts/cookbook_artifact1-1x1/
-/cookbook_artifacts/cookbook_artifact1-1x1/metadata.rb
-/cookbook_artifacts/cookbook_artifact2-2x2/
-/cookbook_artifacts/cookbook_artifact2-2x2/metadata.rb
-/cookbook_artifacts/cookbook_artifact2-2x2/recipes/
-/cookbook_artifacts/cookbook_artifact2-2x2/recipes/default.rb
-/cookbooks/
-/cookbooks/cookbook1/
-/cookbooks/cookbook1/metadata.rb
-/cookbooks/cookbook2/
-/cookbooks/cookbook2/metadata.rb
-/cookbooks/cookbook2/recipes/
-/cookbooks/cookbook2/recipes/default.rb
-/data_bags/
-/data_bags/bag1/
-/data_bags/bag1/item1.json
-/data_bags/bag1/item2.json
-/data_bags/bag2/
-/data_bags/bag2/item1.json
-/data_bags/bag2/item2.json
-/environments/
-/environments/_default.json
-/environments/environment1.json
-/environments/environment2.json
-/groups/
-/groups/admins.json
-/groups/billing-admins.json
-/groups/clients.json
-/groups/group1.json
-/groups/group2.json
-/groups/users.json
-/invitations.json
-/members.json
-/nodes/
-/nodes/node1.json
-/nodes/node2.json
-/org.json
-/policies/
-/policies/policy1-1.2.3.json
-/policies/policy2-1.2.3.json
-/policies/policy2-1.3.5.json
-/policy_groups/
-/policy_groups/policy_group1.json
-/policy_groups/policy_group2.json
-/roles/
-/roles/role1.json
-/roles/role2.json
+ knife("list -Rfp /").should_succeed <<~EOM
+ /acls/
+ /acls/clients/
+ /acls/clients/client1.json
+ /acls/clients/client2.json
+ /acls/clients/foo-validator.json
+ /acls/containers/
+ /acls/containers/clients.json
+ /acls/containers/container1.json
+ /acls/containers/container2.json
+ /acls/containers/containers.json
+ /acls/containers/cookbook_artifacts.json
+ /acls/containers/cookbooks.json
+ /acls/containers/data.json
+ /acls/containers/environments.json
+ /acls/containers/groups.json
+ /acls/containers/nodes.json
+ /acls/containers/policies.json
+ /acls/containers/policy_groups.json
+ /acls/containers/roles.json
+ /acls/containers/sandboxes.json
+ /acls/cookbook_artifacts/
+ /acls/cookbook_artifacts/cookbook_artifact1.json
+ /acls/cookbook_artifacts/cookbook_artifact2.json
+ /acls/cookbooks/
+ /acls/cookbooks/cookbook1.json
+ /acls/cookbooks/cookbook2.json
+ /acls/data_bags/
+ /acls/data_bags/bag1.json
+ /acls/data_bags/bag2.json
+ /acls/environments/
+ /acls/environments/_default.json
+ /acls/environments/environment1.json
+ /acls/environments/environment2.json
+ /acls/groups/
+ /acls/groups/admins.json
+ /acls/groups/billing-admins.json
+ /acls/groups/clients.json
+ /acls/groups/group1.json
+ /acls/groups/group2.json
+ /acls/groups/users.json
+ /acls/nodes/
+ /acls/nodes/node1.json
+ /acls/nodes/node2.json
+ /acls/organization.json
+ /acls/policies/
+ /acls/policies/policy1.json
+ /acls/policies/policy2.json
+ /acls/policy_groups/
+ /acls/policy_groups/policy_group1.json
+ /acls/policy_groups/policy_group2.json
+ /acls/roles/
+ /acls/roles/role1.json
+ /acls/roles/role2.json
+ /clients/
+ /clients/client1.json
+ /clients/client2.json
+ /clients/foo-validator.json
+ /containers/
+ /containers/clients.json
+ /containers/container1.json
+ /containers/container2.json
+ /containers/containers.json
+ /containers/cookbook_artifacts.json
+ /containers/cookbooks.json
+ /containers/data.json
+ /containers/environments.json
+ /containers/groups.json
+ /containers/nodes.json
+ /containers/policies.json
+ /containers/policy_groups.json
+ /containers/roles.json
+ /containers/sandboxes.json
+ /cookbook_artifacts/
+ /cookbook_artifacts/cookbook_artifact1-1x1/
+ /cookbook_artifacts/cookbook_artifact1-1x1/metadata.rb
+ /cookbook_artifacts/cookbook_artifact2-2x2/
+ /cookbook_artifacts/cookbook_artifact2-2x2/metadata.rb
+ /cookbook_artifacts/cookbook_artifact2-2x2/recipes/
+ /cookbook_artifacts/cookbook_artifact2-2x2/recipes/default.rb
+ /cookbooks/
+ /cookbooks/cookbook1/
+ /cookbooks/cookbook1/metadata.rb
+ /cookbooks/cookbook2/
+ /cookbooks/cookbook2/metadata.rb
+ /cookbooks/cookbook2/recipes/
+ /cookbooks/cookbook2/recipes/default.rb
+ /data_bags/
+ /data_bags/bag1/
+ /data_bags/bag1/item1.json
+ /data_bags/bag1/item2.json
+ /data_bags/bag2/
+ /data_bags/bag2/item1.json
+ /data_bags/bag2/item2.json
+ /environments/
+ /environments/_default.json
+ /environments/environment1.json
+ /environments/environment2.json
+ /groups/
+ /groups/admins.json
+ /groups/billing-admins.json
+ /groups/clients.json
+ /groups/group1.json
+ /groups/group2.json
+ /groups/users.json
+ /invitations.json
+ /members.json
+ /nodes/
+ /nodes/node1.json
+ /nodes/node2.json
+ /org.json
+ /policies/
+ /policies/policy1-1.2.3.json
+ /policies/policy2-1.2.3.json
+ /policies/policy2-1.3.5.json
+ /policy_groups/
+ /policy_groups/policy_group1.json
+ /policy_groups/policy_group2.json
+ /roles/
+ /roles/role1.json
+ /roles/role2.json
EOM
end
end
diff --git a/spec/integration/knife/node_bulk_delete_spec.rb b/spec/integration/knife/node_bulk_delete_spec.rb
index fa706cbd2b..501091c0e7 100644
--- a/spec/integration/knife/node_bulk_delete_spec.rb
+++ b/spec/integration/knife/node_bulk_delete_spec.rb
@@ -32,18 +32,18 @@ describe "knife node bulk delete", :workstation do
end
it "deletes all matching nodes" do
- knife("node bulk delete ^ca.*", input: "Y").should_succeed <<EOM
-The following nodes will be deleted:
+ knife("node bulk delete ^ca.*", input: "Y").should_succeed <<~EOM
+ The following nodes will be deleted:
-car cat
+ car cat
-Are you sure you want to delete these nodes? (Y/N) Deleted node car
-Deleted node cat
+ Are you sure you want to delete these nodes? (Y/N) Deleted node car
+ Deleted node cat
EOM
- knife("node list").should_succeed <<EOM
-cdr
-cons
+ knife("node list").should_succeed <<~EOM
+ cdr
+ cons
EOM
end
end
diff --git a/spec/integration/knife/node_delete_spec.rb b/spec/integration/knife/node_delete_spec.rb
index 5d88af6d4f..9d8f382690 100644
--- a/spec/integration/knife/node_delete_spec.rb
+++ b/spec/integration/knife/node_delete_spec.rb
@@ -32,14 +32,14 @@ describe "knife node delete", :workstation do
end
it "deletes a node" do
- knife("node delete car", input: "Y").should_succeed <<EOM
-Do you really want to delete car? (Y/N) Deleted node[car]
+ knife("node delete car", input: "Y").should_succeed <<~EOM
+ Do you really want to delete car? (Y/N) Deleted node[car]
EOM
- knife("node list").should_succeed <<EOM
-cat
-cdr
-cons
+ knife("node list").should_succeed <<~EOM
+ cat
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/node_environment_set_spec.rb b/spec/integration/knife/node_environment_set_spec.rb
index 10fec5723f..09d1828130 100644
--- a/spec/integration/knife/node_environment_set_spec.rb
+++ b/spec/integration/knife/node_environment_set_spec.rb
@@ -31,9 +31,9 @@ describe "knife node environment set", :workstation do
it "sets an environment on a node" do
knife("node environment set cons lisp").should_succeed /chef_environment:.*lisp/
- knife("node show cons -a chef_environment").should_succeed <<EOM
-cons:
- chef_environment: lisp
+ knife("node show cons -a chef_environment").should_succeed <<~EOM
+ cons:
+ chef_environment: lisp
EOM
end
diff --git a/spec/integration/knife/node_from_file_spec.rb b/spec/integration/knife/node_from_file_spec.rb
index 3430967a21..f7a4717e7c 100644
--- a/spec/integration/knife/node_from_file_spec.rb
+++ b/spec/integration/knife/node_from_file_spec.rb
@@ -29,27 +29,27 @@ describe "knife node from file", :workstation do
when_the_repository "has some nodes" do
before do
- file "nodes/cons.json", <<EOM
-{
- "name": "cons",
- "chef_environment": "_default",
- "run_list": [
- "recipe[cons]"
-]
-,
- "normal": {
- "tags": [
-
- ]
- }
-}
+ file "nodes/cons.json", <<~EOM
+ {
+ "name": "cons",
+ "chef_environment": "_default",
+ "run_list": [
+ "recipe[cons]"
+ ]
+ ,
+ "normal": {
+ "tags": [
+
+ ]
+ }
+ }
EOM
end
it "uploads a single file" do
- knife("node from file #{node_dir}/cons.json").should_succeed stderr: <<EOM
-Updated Node cons
+ knife("node from file #{node_dir}/cons.json").should_succeed stderr: <<~EOM
+ Updated Node cons
EOM
end
diff --git a/spec/integration/knife/node_list_spec.rb b/spec/integration/knife/node_list_spec.rb
index 76f5861e03..fd7394f00b 100644
--- a/spec/integration/knife/node_list_spec.rb
+++ b/spec/integration/knife/node_list_spec.rb
@@ -32,11 +32,11 @@ describe "knife node list", :workstation do
end
it "lists all cookbooks" do
- knife("node list").should_succeed <<EOM
-car
-cat
-cdr
-cons
+ knife("node list").should_succeed <<~EOM
+ car
+ cat
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/raw_spec.rb b/spec/integration/knife/raw_spec.rb
index 5e0d3a3d11..1c8239746f 100644
--- a/spec/integration/knife/raw_spec.rb
+++ b/spec/integration/knife/raw_spec.rb
@@ -38,31 +38,31 @@ describe "knife raw", :workstation do
user "x", "{}"
end
- it "knife raw /nodes/x returns the node", :skip => (RUBY_VERSION < "1.9") do
- knife("raw /nodes/x").should_succeed <<EOM
-{
- "name": "x",
- "json_class": "Chef::Node",
- "chef_type": "node",
- "chef_environment": "_default",
- "override": {
-
- },
- "normal": {
- "tags": [
-
- ]
- },
- "default": {
-
- },
- "automatic": {
-
- },
- "run_list": [
-
- ]
-}
+ it "knife raw /nodes/x returns the node", skip: (RUBY_VERSION < "1.9") do
+ knife("raw /nodes/x").should_succeed <<~EOM
+ {
+ "name": "x",
+ "json_class": "Chef::Node",
+ "chef_type": "node",
+ "chef_environment": "_default",
+ "override": {
+
+ },
+ "normal": {
+ "tags": [
+
+ ]
+ },
+ "default": {
+
+ },
+ "automatic": {
+
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -70,116 +70,116 @@ EOM
knife("raw /blarghle").should_fail(/ERROR: Server responded with error 404 "Not Found\s*"/)
end
- it "knife raw -m DELETE /roles/x succeeds", :skip => (RUBY_VERSION < "1.9") do
- knife("raw -m DELETE /roles/x").should_succeed <<EOM
-{
- "name": "x",
- "description": "",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
+ it "knife raw -m DELETE /roles/x succeeds", skip: (RUBY_VERSION < "1.9") do
+ knife("raw -m DELETE /roles/x").should_succeed <<~EOM
+ {
+ "name": "x",
+ "description": "",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
- },
- "override_attributes": {
+ },
+ "override_attributes": {
- },
- "run_list": [
+ },
+ "run_list": [
- ],
- "env_run_lists": {
+ ],
+ "env_run_lists": {
- }
-}
+ }
+ }
EOM
knife("show /roles/x.json").should_fail "ERROR: /roles/x.json: No such file or directory\n"
end
- it "knife raw -m PUT -i blah.txt /roles/x succeeds", :skip => (RUBY_VERSION < "1.9") do
+ it "knife raw -m PUT -i blah.txt /roles/x succeeds", skip: (RUBY_VERSION < "1.9") do
Tempfile.open("raw_put_input") do |file|
- file.write <<EOM
-{
- "name": "x",
- "description": "eek",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
+ file.write <<~EOM
+ {
+ "name": "x",
+ "description": "eek",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
- },
- "override_attributes": {
+ },
+ "override_attributes": {
- },
- "run_list": [
+ },
+ "run_list": [
- ],
- "env_run_lists": {
+ ],
+ "env_run_lists": {
- }
-}
+ }
+ }
EOM
file.close
- knife("raw -m PUT -i #{file.path} /roles/x").should_succeed <<EOM
-{
- "name": "x",
- "description": "eek",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
+ knife("raw -m PUT -i #{file.path} /roles/x").should_succeed <<~EOM
+ {
+ "name": "x",
+ "description": "eek",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
- },
- "override_attributes": {
+ },
+ "override_attributes": {
- },
- "run_list": [
+ },
+ "run_list": [
- ],
- "env_run_lists": {
+ ],
+ "env_run_lists": {
- }
-}
+ }
+ }
EOM
- knife("show /roles/x.json").should_succeed <<EOM
-/roles/x.json:
-{
- "name": "x",
- "description": "eek"
-}
+ knife("show /roles/x.json").should_succeed <<~EOM
+ /roles/x.json:
+ {
+ "name": "x",
+ "description": "eek"
+ }
EOM
end
end
- it "knife raw -m POST -i blah.txt /roles succeeds", :skip => (RUBY_VERSION < "1.9") do
+ it "knife raw -m POST -i blah.txt /roles succeeds", skip: (RUBY_VERSION < "1.9") do
Tempfile.open("raw_put_input") do |file|
- file.write <<EOM
-{
- "name": "y",
- "description": "eek",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
- },
- "override_attributes": {
- },
- "run_list": [
-
- ],
- "env_run_lists": {
- }
-}
+ file.write <<~EOM
+ {
+ "name": "y",
+ "description": "eek",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
+ },
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ],
+ "env_run_lists": {
+ }
+ }
EOM
file.close
- knife("raw -m POST -i #{file.path} /roles").should_succeed <<EOM
-{
- "uri": "#{Chef::Config.chef_server_url}/roles/y"
-}
+ knife("raw -m POST -i #{file.path} /roles").should_succeed <<~EOM
+ {
+ "uri": "#{Chef::Config.chef_server_url}/roles/y"
+ }
EOM
- knife("show /roles/y.json").should_succeed <<EOM
-/roles/y.json:
-{
- "name": "y",
- "description": "eek"
-}
+ knife("show /roles/y.json").should_succeed <<~EOM
+ /roles/y.json:
+ {
+ "name": "y",
+ "description": "eek"
+ }
EOM
end
end
@@ -198,18 +198,18 @@ EOM
@raw_server_thread.kill if @raw_server_thread
end
- it "knife raw /blah returns the prettified json", :skip => (RUBY_VERSION < "1.9") do
- knife("raw /blah").should_succeed <<EOM
-{
- "x": "y",
- "a": "b"
-}
+ it "knife raw /blah returns the prettified json", skip: (RUBY_VERSION < "1.9") do
+ knife("raw /blah").should_succeed <<~EOM
+ {
+ "x": "y",
+ "a": "b"
+ }
EOM
end
it "knife raw --no-pretty /blah returns the raw json" do
- knife("raw --no-pretty /blah").should_succeed <<EOM
-{ "x": "y", "a": "b" }
+ knife("raw --no-pretty /blah").should_succeed <<~EOM
+ { "x": "y", "a": "b" }
EOM
end
end
@@ -229,14 +229,14 @@ EOM
end
it "knife raw /blah returns the raw text" do
- knife("raw /blah").should_succeed(<<EOM)
-{ "x": "y", "a": "b" }
+ knife("raw /blah").should_succeed(<<~EOM)
+ { "x": "y", "a": "b" }
EOM
end
it "knife raw --no-pretty /blah returns the raw text" do
- knife("raw --no-pretty /blah").should_succeed(<<EOM)
-{ "x": "y", "a": "b" }
+ knife("raw --no-pretty /blah").should_succeed(<<~EOM)
+ { "x": "y", "a": "b" }
EOM
end
end
diff --git a/spec/integration/knife/role_bulk_delete_spec.rb b/spec/integration/knife/role_bulk_delete_spec.rb
index 0e7ff941e2..5a88ef282e 100644
--- a/spec/integration/knife/role_bulk_delete_spec.rb
+++ b/spec/integration/knife/role_bulk_delete_spec.rb
@@ -32,18 +32,18 @@ describe "knife role bulk delete", :workstation do
end
it "deletes all matching roles" do
- knife("role bulk delete ^ca.*", input: "Y").should_succeed <<EOM
-The following roles will be deleted:
+ knife("role bulk delete ^ca.*", input: "Y").should_succeed <<~EOM
+ The following roles will be deleted:
-car cat
+ car cat
-Are you sure you want to delete these roles? (Y/N) Deleted role car
-Deleted role cat
+ Are you sure you want to delete these roles? (Y/N) Deleted role car
+ Deleted role cat
EOM
- knife("role list").should_succeed <<EOM
-cdr
-cons
+ knife("role list").should_succeed <<~EOM
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/role_delete_spec.rb b/spec/integration/knife/role_delete_spec.rb
index 9fbd3758b9..875f80cede 100644
--- a/spec/integration/knife/role_delete_spec.rb
+++ b/spec/integration/knife/role_delete_spec.rb
@@ -32,14 +32,14 @@ describe "knife role delete", :workstation do
end
it "deletes a role" do
- knife("role delete car", input: "Y").should_succeed <<EOM
-Do you really want to delete car? (Y/N) Deleted role[car]
+ knife("role delete car", input: "Y").should_succeed <<~EOM
+ Do you really want to delete car? (Y/N) Deleted role[car]
EOM
- knife("role list").should_succeed <<EOM
-cat
-cdr
-cons
+ knife("role list").should_succeed <<~EOM
+ cat
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/role_from_file_spec.rb b/spec/integration/knife/role_from_file_spec.rb
index 60caa3fa88..bc93d0f6e0 100644
--- a/spec/integration/knife/role_from_file_spec.rb
+++ b/spec/integration/knife/role_from_file_spec.rb
@@ -29,64 +29,64 @@ describe "knife role from file", :workstation do
when_the_repository "has some roles" do
before do
- file "roles/cons.json", <<EOM
-{
- "name": "cons",
- "description": "An role",
- "json_class": "Chef::role",
- "chef_type": "role",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
+ file "roles/cons.json", <<~EOM
+ {
+ "name": "cons",
+ "description": "An role",
+ "json_class": "Chef::role",
+ "chef_type": "role",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
- }
-}
+ }
+ }
EOM
- file "roles/car.json", <<EOM
-{
- "name": "car",
- "description": "A role for list nodes",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
+ file "roles/car.json", <<~EOM
+ {
+ "name": "car",
+ "description": "A role for list nodes",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
- }
-}
+ }
+ }
EOM
- file "roles/cdr.json", <<EOM
-{
- "name": "cdr",
- "description": "A role for last nodes",
- "json_class": "Chef::Role",
- "chef_type": "role",
- "default_attributes": {
- "hola": "Amigos!"
- },
- "override_attributes": {
+ file "roles/cdr.json", <<~EOM
+ {
+ "name": "cdr",
+ "description": "A role for last nodes",
+ "json_class": "Chef::Role",
+ "chef_type": "role",
+ "default_attributes": {
+ "hola": "Amigos!"
+ },
+ "override_attributes": {
- }
-}
+ }
+ }
EOM
end
it "uploads a single file" do
- knife("role from file #{role_dir}/cons.json").should_succeed stderr: <<EOM
-Updated Role cons
+ knife("role from file #{role_dir}/cons.json").should_succeed stderr: <<~EOM
+ Updated Role cons
EOM
end
it "uploads many files" do
- knife("role from file #{role_dir}/cons.json #{role_dir}/car.json #{role_dir}/cdr.json").should_succeed stderr: <<EOM
-Updated Role cons
-Updated Role car
-Updated Role cdr
+ knife("role from file #{role_dir}/cons.json #{role_dir}/car.json #{role_dir}/cdr.json").should_succeed stderr: <<~EOM
+ Updated Role cons
+ Updated Role car
+ Updated Role cdr
EOM
end
diff --git a/spec/integration/knife/role_list_spec.rb b/spec/integration/knife/role_list_spec.rb
index 36dc76be4c..db13e521b5 100644
--- a/spec/integration/knife/role_list_spec.rb
+++ b/spec/integration/knife/role_list_spec.rb
@@ -32,11 +32,11 @@ describe "knife role list", :workstation do
end
it "lists all cookbooks" do
- knife("role list").should_succeed <<EOM
-car
-cat
-cdr
-cons
+ knife("role list").should_succeed <<~EOM
+ car
+ cat
+ cdr
+ cons
EOM
end
diff --git a/spec/integration/knife/role_show_spec.rb b/spec/integration/knife/role_show_spec.rb
index f655c03e8d..c2f5efedaf 100644
--- a/spec/integration/knife/role_show_spec.rb
+++ b/spec/integration/knife/role_show_spec.rb
@@ -33,15 +33,15 @@ describe "knife role show", :workstation do
# rubocop:disable Layout/TrailingWhitespace
it "shows a cookbook" do
- knife("role show cons").should_succeed <<EOM
-chef_type: role
-default_attributes:
-description:
-env_run_lists:
-json_class: Chef::Role
-name: cons
-override_attributes:
-run_list:
+ knife("role show cons").should_succeed <<~EOM
+ chef_type: role
+ default_attributes:
+ description:
+ env_run_lists:
+ json_class: Chef::Role
+ name: cons
+ override_attributes:
+ run_list:
EOM
end
# rubocop:enable Layout/TrailingWhitespace
diff --git a/spec/integration/knife/show_spec.rb b/spec/integration/knife/show_spec.rb
index ed4802fef9..df9f55fbf2 100644
--- a/spec/integration/knife/show_spec.rb
+++ b/spec/integration/knife/show_spec.rb
@@ -49,63 +49,63 @@ describe "knife show", :workstation do
end
it "knife show /cookbooks/x/metadata.rb shows the remote version" do
- knife("show /cookbooks/x/metadata.rb").should_succeed <<EOM
-/cookbooks/x/metadata.rb:
-name "x"; version "1.0.0"
+ knife("show /cookbooks/x/metadata.rb").should_succeed <<~EOM
+ /cookbooks/x/metadata.rb:
+ name "x"; version "1.0.0"
EOM
end
it "knife show --local /cookbooks/x/metadata.rb shows the local version" do
- knife("show --local /cookbooks/x/metadata.rb").should_succeed <<EOM
-/cookbooks/x/metadata.rb:
-name "x"; version "1.0.0"
+ knife("show --local /cookbooks/x/metadata.rb").should_succeed <<~EOM
+ /cookbooks/x/metadata.rb:
+ name "x"; version "1.0.0"
EOM
end
it "knife show /data_bags/x/y.json shows the remote version" do
- knife("show /data_bags/x/y.json").should_succeed <<EOM
-/data_bags/x/y.json:
-{
- "id": "y"
-}
+ knife("show /data_bags/x/y.json").should_succeed <<~EOM
+ /data_bags/x/y.json:
+ {
+ "id": "y"
+ }
EOM
end
it "knife show --local /data_bags/x/y.json shows the local version" do
- knife("show --local /data_bags/x/y.json").should_succeed <<EOM
-/data_bags/x/y.json:
-{
- "foo": "bar"
-}
+ knife("show --local /data_bags/x/y.json").should_succeed <<~EOM
+ /data_bags/x/y.json:
+ {
+ "foo": "bar"
+ }
EOM
end
- it "knife show /environments/x.json shows the remote version", :skip => (RUBY_VERSION < "1.9") do
- knife("show /environments/x.json").should_succeed <<EOM
-/environments/x.json:
-{
- "name": "x"
-}
+ it "knife show /environments/x.json shows the remote version", skip: (RUBY_VERSION < "1.9") do
+ knife("show /environments/x.json").should_succeed <<~EOM
+ /environments/x.json:
+ {
+ "name": "x"
+ }
EOM
end
it "knife show --local /environments/x.json shows the local version" do
- knife("show --local /environments/x.json").should_succeed <<EOM
-/environments/x.json:
-{
- "foo": "bar"
-}
+ knife("show --local /environments/x.json").should_succeed <<~EOM
+ /environments/x.json:
+ {
+ "foo": "bar"
+ }
EOM
end
- it "knife show /roles/x.json shows the remote version", :skip => (RUBY_VERSION < "1.9") do
- knife("show /roles/x.json").should_succeed <<EOM
-/roles/x.json:
-{
- "name": "x"
-}
+ it "knife show /roles/x.json shows the remote version", skip: (RUBY_VERSION < "1.9") do
+ knife("show /roles/x.json").should_succeed <<~EOM
+ /roles/x.json:
+ {
+ "name": "x"
+ }
EOM
end
it "knife show --local /roles/x.json shows the local version" do
- knife("show --local /roles/x.json").should_succeed <<EOM
-/roles/x.json:
-{
- "foo": "bar"
-}
+ knife("show --local /roles/x.json").should_succeed <<~EOM
+ /roles/x.json:
+ {
+ "foo": "bar"
+ }
EOM
end
# show directory
@@ -135,22 +135,22 @@ EOM
"name" => "x",
}
end
- it "knife show shows the attributes in a predetermined order", :skip => (RUBY_VERSION < "1.9") do
- knife("show /environments/x.json").should_succeed <<EOM
-/environments/x.json:
-{
- "name": "x",
- "description": "woo",
- "cookbook_versions": {
- "blah": "= 1.0.0"
- },
- "default_attributes": {
- "foo": "bar"
- },
- "override_attributes": {
- "x": "y"
- }
-}
+ it "knife show shows the attributes in a predetermined order", skip: (RUBY_VERSION < "1.9") do
+ knife("show /environments/x.json").should_succeed <<~EOM
+ /environments/x.json:
+ {
+ "name": "x",
+ "description": "woo",
+ "cookbook_versions": {
+ "blah": "= 1.0.0"
+ },
+ "default_attributes": {
+ "foo": "bar"
+ },
+ "override_attributes": {
+ "x": "y"
+ }
+ }
EOM
end
end
@@ -158,9 +158,9 @@ EOM
when_the_repository "has an environment with bad JSON" do
before { file "environments/x.json", "{" }
it "knife show succeeds" do
- knife("show --local /environments/x.json").should_succeed <<EOM
-/environments/x.json:
-{
+ knife("show --local /environments/x.json").should_succeed <<~EOM
+ /environments/x.json:
+ {
EOM
end
end
diff --git a/spec/integration/knife/upload_spec.rb b/spec/integration/knife/upload_spec.rb
index dc713d02b3..647c7773f9 100644
--- a/spec/integration/knife/upload_spec.rb
+++ b/spec/integration/knife/upload_spec.rb
@@ -52,36 +52,36 @@ describe "knife upload", :workstation do
it "knife upload does nothing" do
knife("upload /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients/chef-validator.json
-D\t/clients/chef-webui.json
-D\t/clients/x.json
-D\t/cookbooks/x
-D\t/data_bags/x
-D\t/environments/_default.json
-D\t/environments/x.json
-D\t/nodes/x.json
-D\t/roles/x.json
-D\t/users/admin.json
-D\t/users/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients/chef-validator.json
+ D\t/clients/chef-webui.json
+ D\t/clients/x.json
+ D\t/cookbooks/x
+ D\t/data_bags/x
+ D\t/environments/_default.json
+ D\t/environments/x.json
+ D\t/nodes/x.json
+ D\t/roles/x.json
+ D\t/users/admin.json
+ D\t/users/x.json
EOM
end
it "knife upload --purge deletes everything" do
- knife("upload --purge /").should_succeed(<<EOM, :stderr => "WARNING: /environments/_default.json cannot be deleted (default environment cannot be modified).\n")
-Deleted extra entry /clients/chef-validator.json (purge is on)
-Deleted extra entry /clients/chef-webui.json (purge is on)
-Deleted extra entry /clients/x.json (purge is on)
-Deleted extra entry /cookbooks/x (purge is on)
-Deleted extra entry /data_bags/x (purge is on)
-Deleted extra entry /environments/x.json (purge is on)
-Deleted extra entry /nodes/x.json (purge is on)
-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 <<EOM
-D\t/environments/_default.json
+ knife("upload --purge /").should_succeed(<<~EOM, stderr: "WARNING: /environments/_default.json cannot be deleted (default environment cannot be modified).\n")
+ Deleted extra entry /clients/chef-validator.json (purge is on)
+ Deleted extra entry /clients/chef-webui.json (purge is on)
+ Deleted extra entry /clients/x.json (purge is on)
+ Deleted extra entry /cookbooks/x (purge is on)
+ Deleted extra entry /data_bags/x (purge is on)
+ Deleted extra entry /environments/x.json (purge is on)
+ Deleted extra entry /nodes/x.json (purge is on)
+ 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 <<~EOM
+ D\t/environments/_default.json
EOM
end
end
@@ -129,22 +129,22 @@ EOM
context "except the role file is textually different, but not ACTUALLY different" do
before do
- file "roles/x.json", <<EOM
-{
- "chef_type": "role",
- "default_attributes": {
- },
- "env_run_lists": {
- },
- "json_class": "Chef::Role",
- "name": "x",
- "description": "",
- "override_attributes": {
- },
- "run_list": [
-
- ]
-}
+ file "roles/x.json", <<~EOM
+ {
+ "chef_type": "role",
+ "default_attributes": {
+ },
+ "env_run_lists": {
+ },
+ "json_class": "Chef::Role",
+ "name": "x",
+ "description": "",
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -156,9 +156,9 @@ EOM
context "the role is in ruby" do
before do
- file "roles/x.rb", <<EOM
-name "x"
-description "blargle"
+ file "roles/x.rb", <<~EOM
+ name "x"
+ description "blargle"
EOM
end
@@ -197,33 +197,33 @@ EOM
end
it "knife upload adds the new files" do
- knife("upload /").should_succeed <<EOM
-Created /clients/y.json
-Updated /cookbooks/x
-Created /cookbooks/y
-Created /data_bags/x/z.json
-Created /data_bags/y
-Created /data_bags/y/zz.json
-Created /environments/y.json
-Created /nodes/y.json
-Created /roles/y.json
-Created /users/y.json
+ knife("upload /").should_succeed <<~EOM
+ Created /clients/y.json
+ Updated /cookbooks/x
+ Created /cookbooks/y
+ Created /data_bags/x/z.json
+ Created /data_bags/y
+ Created /data_bags/y/zz.json
+ Created /environments/y.json
+ Created /nodes/y.json
+ Created /roles/y.json
+ Created /users/y.json
EOM
knife("diff /").should_succeed ""
end
it "knife upload --no-diff adds the new files" do
- knife("upload --no-diff /").should_succeed <<EOM
-Created /clients/y.json
-Updated /cookbooks/x
-Created /cookbooks/y
-Created /data_bags/x/z.json
-Created /data_bags/y
-Created /data_bags/y/zz.json
-Created /environments/y.json
-Created /nodes/y.json
-Created /roles/y.json
-Created /users/y.json
+ knife("upload --no-diff /").should_succeed <<~EOM
+ Created /clients/y.json
+ Updated /cookbooks/x
+ Created /cookbooks/y
+ Created /data_bags/x/z.json
+ Created /data_bags/y
+ Created /data_bags/y/zz.json
+ Created /environments/y.json
+ Created /nodes/y.json
+ Created /roles/y.json
+ Created /users/y.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -233,35 +233,35 @@ EOM
when_the_repository "is empty" do
it "knife upload does nothing" do
knife("upload /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
it "knife upload --purge deletes nothing" do
- knife("upload --purge /").should_fail <<EOM
-ERROR: /clients cannot be deleted.
-ERROR: /cookbooks cannot be deleted.
-ERROR: /data_bags cannot be deleted.
-ERROR: /environments cannot be deleted.
-ERROR: /nodes cannot be deleted.
-ERROR: /roles cannot be deleted.
-ERROR: /users cannot be deleted.
-EOM
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("upload --purge /").should_fail <<~EOM
+ ERROR: /clients cannot be deleted.
+ ERROR: /cookbooks cannot be deleted.
+ ERROR: /data_bags cannot be deleted.
+ ERROR: /environments cannot be deleted.
+ ERROR: /nodes cannot be deleted.
+ ERROR: /roles cannot be deleted.
+ ERROR: /users cannot be deleted.
+EOM
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
@@ -271,7 +271,7 @@ EOM
end
it "knife upload with no parameters reports an error" do
- knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", :stdout => /USAGE/
+ knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", stdout: /USAGE/
end
end
end
@@ -285,19 +285,19 @@ EOM
end
it "knife upload of the data bag uploads only the values in the data bag item and no other" do
- knife("upload /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("upload /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
knife("diff --name-status /data_bags").should_succeed <<EOM
EOM
- expect(Chef::JSONCompat.parse(knife("raw /data/x/y").stdout, :create_additions => false).keys.sort).to eq(%w{foo id})
+ expect(Chef::JSONCompat.parse(knife("raw /data/x/y").stdout, create_additions: false).keys.sort).to eq(%w{foo id})
end
it "knife upload /data_bags/x /data_bags/x/y.json uploads x once" do
- knife("upload /data_bags/x /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("upload /data_bags/x /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
end
end
@@ -309,12 +309,12 @@ EOM
end
it "upload preserves chef_type and data_bag" do
- knife("upload /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("upload /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
knife("diff --name-status /data_bags").should_succeed ""
- result = Chef::JSONCompat.parse(knife("raw /data/x/y").stdout, :create_additions => false)
+ result = Chef::JSONCompat.parse(knife("raw /data/x/y").stdout, create_additions: false)
expect(result.keys.sort).to eq(%w{chef_type data_bag id})
expect(result["chef_type"]).to eq("aaa")
expect(result["data_bag"]).to eq("bbb")
@@ -328,12 +328,12 @@ EOM
file "data_bags/x/z.json", {}
end
it "knife upload of one data bag item itself succeeds" do
- knife("upload /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("upload /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-A\t/data_bags/x/z.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ A\t/data_bags/x/z.json
EOM
end
end
@@ -353,62 +353,62 @@ EOM
end
it "knife upload of the modified file succeeds" do
- knife("upload /data_bags/x/modified.json").should_succeed <<EOM
-Updated /data_bags/x/modified.json
+ knife("upload /data_bags/x/modified.json").should_succeed <<~EOM
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the unmodified file does nothing" do
knife("upload /data_bags/x/unmodified.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the added file succeeds" do
- knife("upload /data_bags/x/added.json").should_succeed <<EOM
-Created /data_bags/x/added.json
+ knife("upload /data_bags/x/added.json").should_succeed <<~EOM
+ Created /data_bags/x/added.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
EOM
end
it "knife upload of the deleted file does nothing" do
knife("upload /data_bags/x/deleted.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload --purge of the deleted file deletes it" do
- knife("upload --purge /data_bags/x/deleted.json").should_succeed <<EOM
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("upload --purge /data_bags/x/deleted.json").should_succeed <<~EOM
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the entire data bag uploads everything" do
- knife("upload /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
+ knife("upload /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
EOM
end
it "knife upload --purge of the entire data bag uploads everything" do
- knife("upload --purge /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("upload --purge /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -419,22 +419,22 @@ EOM
end
it "knife upload fails" do
- knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", :stdout => /USAGE/
+ knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", stdout: /USAGE/
end
it "knife upload --purge . uploads everything" do
- knife("upload --purge .").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("upload --purge .").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
it "knife upload --purge * uploads everything" do
- knife("upload --purge *").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("upload --purge *").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -466,14 +466,14 @@ EOM
# technically we shouldn't have deleted missing files. But ... cookbooks
# are a special case.
it "knife upload of the cookbook itself succeeds" do
- knife("upload /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
it "knife upload --purge of the cookbook itself succeeds" do
- knife("upload /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -485,8 +485,8 @@ EOM
end
it "knife upload of the cookbook succeeds" do
- knife("upload /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -500,8 +500,8 @@ EOM
end
it "knife upload of the cookbook succeeds" do
- knife("upload /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -513,8 +513,8 @@ EOM
end
it "knife upload --freeze freezes the cookbook" do
- knife("upload --freeze /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload --freeze /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
# Modify a file and attempt to upload
file "cookbooks/x/metadata.rb", 'name "x"; version "1.0.0"#different'
@@ -525,7 +525,7 @@ EOM
when_the_chef_server "has a frozen cookbook" do
before do
- cookbook "frozencook", "1.0.0", {}, :frozen => true
+ cookbook "frozencook", "1.0.0", {}, frozen: true
end
when_the_repository "has an update to said cookbook" do
@@ -538,8 +538,8 @@ EOM
knife("upload /cookbooks/frozencook").should_fail "ERROR: /cookbooks failed to write: Cookbook frozencook is frozen\n"
end
it "knife upload --force uploads the frozen cookbook" do
- knife("upload --force /cookbooks/frozencook").should_succeed <<EOM
-Updated /cookbooks/frozencook
+ knife("upload --force /cookbooks/frozencook").should_succeed <<~EOM
+ Updated /cookbooks/frozencook
EOM
end
end
@@ -558,18 +558,18 @@ EOM
end
it "knife upload /cookbooks/x uploads the local version" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
- knife("upload --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
end
@@ -581,8 +581,8 @@ EOM
end
it "knife upload /cookbooks/x uploads the local version" do
- knife("upload --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -594,18 +594,18 @@ EOM
end
it "knife upload /cookbooks/x uploads the local version" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
- knife("upload --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x/metadata.rb
-D\t/cookbooks/x/onlyin1.0.1.rb
-A\t/cookbooks/x/onlyin1.0.0.rb
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x/metadata.rb
+ D\t/cookbooks/x/onlyin1.0.1.rb
+ A\t/cookbooks/x/onlyin1.0.0.rb
EOM
end
end
@@ -616,8 +616,8 @@ EOM
end
it "knife upload /cookbooks/x uploads the new version" do
- knife("upload --purge /cookbooks/x").should_succeed <<EOM
-Updated /cookbooks/x
+ knife("upload --purge /cookbooks/x").should_succeed <<~EOM
+ Updated /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -635,24 +635,24 @@ EOM
end
it "knife upload tries and fails" do
- error1 = <<-EOH
-WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
- {
- (right here) ------^
-
-ERROR: /environments/x.json failed to write: Parse error reading JSON: parse error: premature EOF
- {
- (right here) ------^
+ error1 = <<~EOH
+ WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ {
+ (right here) ------^
+
+ ERROR: /environments/x.json failed to write: Parse error reading JSON: parse error: premature EOF
+ {
+ (right here) ------^
EOH
- warn = <<-EOH
-WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
- {
- (right here) ------^
+ warn = <<~EOH
+ WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error: premature EOF
+ {
+ (right here) ------^
EOH
knife("upload /environments/x.json").should_fail(error1)
- knife("diff --name-status /environments/x.json").should_succeed("M\t/environments/x.json\n", :stderr => warn)
+ knife("diff --name-status /environments/x.json").should_succeed("M\t/environments/x.json\n", stderr: warn)
end
end
@@ -716,8 +716,8 @@ WARN: Parse error reading #{path_to('environments/x.json')} as JSON: parse error
file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\nchef_version '~> 999.0'")
end
it "knife upload succeeds" do
- knife("upload /cookbooks/x").should_succeed <<EOM
-Created /cookbooks/x
+ knife("upload /cookbooks/x").should_succeed <<~EOM
+ Created /cookbooks/x
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -751,36 +751,36 @@ EOM
it "knife upload does nothing" do
knife("upload /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients/chef-validator.json
-D\t/clients/chef-webui.json
-D\t/clients/x.json
-D\t/cookbooks/x-1.0.0
-D\t/data_bags/x
-D\t/environments/_default.json
-D\t/environments/x.json
-D\t/nodes/x.json
-D\t/roles/x.json
-D\t/users/admin.json
-D\t/users/x.json
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients/chef-validator.json
+ D\t/clients/chef-webui.json
+ D\t/clients/x.json
+ D\t/cookbooks/x-1.0.0
+ D\t/data_bags/x
+ D\t/environments/_default.json
+ D\t/environments/x.json
+ D\t/nodes/x.json
+ D\t/roles/x.json
+ D\t/users/admin.json
+ D\t/users/x.json
EOM
end
it "knife upload --purge deletes everything" do
- knife("upload --purge /").should_succeed(<<EOM, :stderr => "WARNING: /environments/_default.json cannot be deleted (default environment cannot be modified).\n")
-Deleted extra entry /clients/chef-validator.json (purge is on)
-Deleted extra entry /clients/chef-webui.json (purge is on)
-Deleted extra entry /clients/x.json (purge is on)
-Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
-Deleted extra entry /data_bags/x (purge is on)
-Deleted extra entry /environments/x.json (purge is on)
-Deleted extra entry /nodes/x.json (purge is on)
-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 <<EOM
-D\t/environments/_default.json
+ knife("upload --purge /").should_succeed(<<~EOM, stderr: "WARNING: /environments/_default.json cannot be deleted (default environment cannot be modified).\n")
+ Deleted extra entry /clients/chef-validator.json (purge is on)
+ Deleted extra entry /clients/chef-webui.json (purge is on)
+ Deleted extra entry /clients/x.json (purge is on)
+ Deleted extra entry /cookbooks/x-1.0.0 (purge is on)
+ Deleted extra entry /data_bags/x (purge is on)
+ Deleted extra entry /environments/x.json (purge is on)
+ Deleted extra entry /nodes/x.json (purge is on)
+ 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 <<~EOM
+ D\t/environments/_default.json
EOM
end
end
@@ -824,22 +824,22 @@ EOM
context "except the role file is textually different, but not ACTUALLY different" do
before do
- file "roles/x.json", <<EOM
-{
- "chef_type": "role",
- "default_attributes": {
- },
- "env_run_lists": {
- },
- "json_class": "Chef::Role",
- "name": "x",
- "description": "",
- "override_attributes": {
- },
- "run_list": [
-
- ]
-}
+ file "roles/x.json", <<~EOM
+ {
+ "chef_type": "role",
+ "default_attributes": {
+ },
+ "env_run_lists": {
+ },
+ "json_class": "Chef::Role",
+ "name": "x",
+ "description": "",
+ "override_attributes": {
+ },
+ "run_list": [
+
+ ]
+ }
EOM
end
@@ -864,18 +864,18 @@ EOM
end
it "knife upload adds the new files" do
- knife("upload /").should_succeed <<EOM
-Created /clients/y.json
-Updated /cookbooks/x-1.0.0
-Created /cookbooks/x-2.0.0
-Created /cookbooks/y-1.0.0
-Created /data_bags/x/z.json
-Created /data_bags/y
-Created /data_bags/y/zz.json
-Created /environments/y.json
-Created /nodes/y.json
-Created /roles/y.json
-Created /users/y.json
+ knife("upload /").should_succeed <<~EOM
+ Created /clients/y.json
+ Updated /cookbooks/x-1.0.0
+ Created /cookbooks/x-2.0.0
+ Created /cookbooks/y-1.0.0
+ Created /data_bags/x/z.json
+ Created /data_bags/y
+ Created /data_bags/y/zz.json
+ Created /environments/y.json
+ Created /nodes/y.json
+ Created /roles/y.json
+ Created /users/y.json
EOM
knife("diff --name-status /").should_succeed ""
end
@@ -885,35 +885,35 @@ EOM
when_the_repository "is empty" do
it "knife upload does nothing" do
knife("upload /").should_succeed ""
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
it "knife upload --purge deletes nothing" do
- knife("upload --purge /").should_fail <<EOM
-ERROR: /clients cannot be deleted.
-ERROR: /cookbooks cannot be deleted.
-ERROR: /data_bags cannot be deleted.
-ERROR: /environments cannot be deleted.
-ERROR: /nodes cannot be deleted.
-ERROR: /roles cannot be deleted.
-ERROR: /users cannot be deleted.
-EOM
- knife("diff --name-status /").should_succeed <<EOM
-D\t/clients
-D\t/cookbooks
-D\t/data_bags
-D\t/environments
-D\t/nodes
-D\t/roles
-D\t/users
+ knife("upload --purge /").should_fail <<~EOM
+ ERROR: /clients cannot be deleted.
+ ERROR: /cookbooks cannot be deleted.
+ ERROR: /data_bags cannot be deleted.
+ ERROR: /environments cannot be deleted.
+ ERROR: /nodes cannot be deleted.
+ ERROR: /roles cannot be deleted.
+ ERROR: /users cannot be deleted.
+EOM
+ knife("diff --name-status /").should_succeed <<~EOM
+ D\t/clients
+ D\t/cookbooks
+ D\t/data_bags
+ D\t/environments
+ D\t/nodes
+ D\t/roles
+ D\t/users
EOM
end
@@ -922,7 +922,7 @@ EOM
cwd "."
end
it "knife upload with no parameters reports an error" do
- knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", :stdout => /USAGE/
+ knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", stdout: /USAGE/
end
end
end
@@ -937,12 +937,12 @@ EOM
end
it "knife upload of one data bag item itself succeeds" do
- knife("upload /data_bags/x/y.json").should_succeed <<EOM
-Created /data_bags/x
-Created /data_bags/x/y.json
+ knife("upload /data_bags/x/y.json").should_succeed <<~EOM
+ Created /data_bags/x
+ Created /data_bags/x/y.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-A\t/data_bags/x/z.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ A\t/data_bags/x/z.json
EOM
end
end
@@ -960,62 +960,62 @@ EOM
end
it "knife upload of the modified file succeeds" do
- knife("upload /data_bags/x/modified.json").should_succeed <<EOM
-Updated /data_bags/x/modified.json
+ knife("upload /data_bags/x/modified.json").should_succeed <<~EOM
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the unmodified file does nothing" do
knife("upload /data_bags/x/unmodified.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the added file succeeds" do
- knife("upload /data_bags/x/added.json").should_succeed <<EOM
-Created /data_bags/x/added.json
+ knife("upload /data_bags/x/added.json").should_succeed <<~EOM
+ Created /data_bags/x/added.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
EOM
end
it "knife upload of the deleted file does nothing" do
knife("upload /data_bags/x/deleted.json").should_succeed ""
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload --purge of the deleted file deletes it" do
- knife("upload --purge /data_bags/x/deleted.json").should_succeed <<EOM
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("upload --purge /data_bags/x/deleted.json").should_succeed <<~EOM
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-M\t/data_bags/x/modified.json
-A\t/data_bags/x/added.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ M\t/data_bags/x/modified.json
+ A\t/data_bags/x/added.json
EOM
end
it "knife upload of the entire data bag uploads everything" do
- knife("upload /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
+ knife("upload /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
EOM
- knife("diff --name-status /data_bags").should_succeed <<EOM
-D\t/data_bags/x/deleted.json
+ knife("diff --name-status /data_bags").should_succeed <<~EOM
+ D\t/data_bags/x/deleted.json
EOM
end
it "knife upload --purge of the entire data bag uploads everything" do
- knife("upload --purge /data_bags/x").should_succeed <<EOM
-Created /data_bags/x/added.json
-Updated /data_bags/x/modified.json
-Deleted extra entry /data_bags/x/deleted.json (purge is on)
+ knife("upload --purge /data_bags/x").should_succeed <<~EOM
+ Created /data_bags/x/added.json
+ Updated /data_bags/x/modified.json
+ Deleted extra entry /data_bags/x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -1024,21 +1024,21 @@ EOM
cwd "data_bags"
end
it "knife upload fails" do
- knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", :stdout => /USAGE/
+ knife("upload").should_fail "FATAL: You must specify at least one argument. If you want to upload everything in this directory, run \"knife upload .\"\n", stdout: /USAGE/
end
it "knife upload --purge . uploads everything" do
- knife("upload --purge .").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("upload --purge .").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
it "knife upload --purge * uploads everything" do
- knife("upload --purge *").should_succeed <<EOM
-Created x/added.json
-Updated x/modified.json
-Deleted extra entry x/deleted.json (purge is on)
+ knife("upload --purge *").should_succeed <<~EOM
+ Created x/added.json
+ Updated x/modified.json
+ Deleted extra entry x/deleted.json (purge is on)
EOM
knife("diff --name-status /data_bags").should_succeed ""
end
@@ -1070,15 +1070,15 @@ EOM
# technically we shouldn't have deleted missing files. But ... cookbooks
# are a special case.
it "knife upload of the cookbook itself succeeds" do
- knife("upload /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
+ knife("upload /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
it "knife upload --purge of the cookbook itself succeeds" do
- knife("upload /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
+ knife("upload /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1090,8 +1090,8 @@ EOM
end
it "knife upload of the cookbook succeeds" do
- knife("upload /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
+ knife("upload /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1105,8 +1105,8 @@ EOM
end
it "knife upload of the cookbook succeeds" do
- knife("upload /cookbooks/x-1.0.0").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
+ knife("upload /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1126,13 +1126,13 @@ EOM
end
it "knife upload /cookbooks uploads the local version" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-M\t/cookbooks/x-1.0.0/onlyin1.0.0.rb
-D\t/cookbooks/x-1.0.1
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ M\t/cookbooks/x-1.0.0/onlyin1.0.0.rb
+ D\t/cookbooks/x-1.0.1
EOM
- knife("upload --purge /cookbooks").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
-Deleted extra entry /cookbooks/x-1.0.1 (purge is on)
+ knife("upload --purge /cookbooks").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
+ Deleted extra entry /cookbooks/x-1.0.1 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1144,9 +1144,9 @@ EOM
cookbook "x", "0.9.9", { "onlyin0.9.9.rb" => "hi" }
end
it "knife upload /cookbooks uploads the local version" do
- knife("upload --purge /cookbooks").should_succeed <<EOM
-Updated /cookbooks/x-1.0.0
-Deleted extra entry /cookbooks/x-0.9.9 (purge is on)
+ knife("upload --purge /cookbooks").should_succeed <<~EOM
+ Updated /cookbooks/x-1.0.0
+ Deleted extra entry /cookbooks/x-0.9.9 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1158,13 +1158,13 @@ EOM
end
it "knife upload /cookbooks/x uploads the local version" do
- knife("diff --name-status /cookbooks").should_succeed <<EOM
-D\t/cookbooks/x-1.0.1
-A\t/cookbooks/x-1.0.0
+ knife("diff --name-status /cookbooks").should_succeed <<~EOM
+ D\t/cookbooks/x-1.0.1
+ A\t/cookbooks/x-1.0.0
EOM
- knife("upload --purge /cookbooks").should_succeed <<EOM
-Created /cookbooks/x-1.0.0
-Deleted extra entry /cookbooks/x-1.0.1 (purge is on)
+ knife("upload --purge /cookbooks").should_succeed <<~EOM
+ Created /cookbooks/x-1.0.0
+ Deleted extra entry /cookbooks/x-1.0.1 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1176,9 +1176,9 @@ EOM
end
it "knife upload /cookbooks/x uploads the new version" do
- knife("upload --purge /cookbooks").should_succeed <<EOM
-Created /cookbooks/x-1.0.0
-Deleted extra entry /cookbooks/x-0.9.9 (purge is on)
+ knife("upload --purge /cookbooks").should_succeed <<~EOM
+ Created /cookbooks/x-1.0.0
+ Deleted extra entry /cookbooks/x-0.9.9 (purge is on)
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1250,8 +1250,8 @@ EOM
file "cookbooks/x-1.0.0/metadata.rb", cb_metadata("x", "1.0.0", "\nchef_version '~> 999.0'")
end
it "knife upload succeeds" do
- knife("upload /cookbooks/x-1.0.0").should_succeed <<EOM
-Created /cookbooks/x-1.0.0
+ knife("upload /cookbooks/x-1.0.0").should_succeed <<~EOM
+ Created /cookbooks/x-1.0.0
EOM
knife("diff --name-status /cookbooks").should_succeed ""
end
@@ -1274,7 +1274,7 @@ EOM
end
end
- when_the_chef_server "is in Enterprise mode", :osc_compat => false, :single_org => false do
+ when_the_chef_server "is in Enterprise mode", osc_compat: false, single_org: false do
before do
user "foo", {}
user "bar", {}
@@ -1313,24 +1313,24 @@ EOM
end
it "knife upload / uploads everything" do
- knife("upload /").should_succeed <<EOM
-Updated /acls/groups/blah.json
-Created /clients/x.json
-Created /containers/x.json
-Created /cookbook_artifacts/x-1x1
-Created /cookbooks/x
-Created /data_bags/x
-Created /data_bags/x/y.json
-Created /environments/x.json
-Created /groups/x.json
-Updated /invitations.json
-Updated /members.json
-Created /nodes/x.json
-Updated /org.json
-Created /policies/blah-1.0.0.json
-Created /policies/x-1.0.0.json
-Created /policy_groups/x.json
-Created /roles/x.json
+ knife("upload /").should_succeed <<~EOM
+ Updated /acls/groups/blah.json
+ Created /clients/x.json
+ Created /containers/x.json
+ Created /cookbook_artifacts/x-1x1
+ Created /cookbooks/x
+ Created /data_bags/x
+ Created /data_bags/x/y.json
+ Created /environments/x.json
+ Created /groups/x.json
+ Updated /invitations.json
+ Updated /members.json
+ Created /nodes/x.json
+ Updated /org.json
+ Created /policies/blah-1.0.0.json
+ Created /policies/x-1.0.0.json
+ Created /policy_groups/x.json
+ Created /roles/x.json
EOM
expect(api.get("association_requests").map { |a| a["username"] }).to eq([ "foo" ])
expect(api.get("users").map { |a| a["user"]["username"] }).to eq([ "bar" ])
@@ -1366,8 +1366,8 @@ EOM
end
it "knife upload makes no changes" do
- knife("upload /").should_succeed <<EOM
-Updated /acls/groups/blah.json
+ knife("upload /").should_succeed <<~EOM
+ Updated /acls/groups/blah.json
EOM
end
end
@@ -1378,8 +1378,8 @@ EOM
end
it "should fail because policies are not updateable" do
- knife("upload /policies/x-1.0.0.json").should_fail <<EOM
-ERROR: /policies/x-1.0.0.json cannot be updated: policy revisions are immutable once uploaded. If you want to change the policy, create a new revision with your changes.
+ knife("upload /policies/x-1.0.0.json").should_fail <<~EOM
+ ERROR: /policies/x-1.0.0.json cannot be updated: policy revisions are immutable once uploaded. If you want to change the policy, create a new revision with your changes.
EOM
end
end
@@ -1390,8 +1390,8 @@ EOM
end
it "should fail because cookbook_artifacts cannot be updated" do
- knife("upload /cookbook_artifacts/x-1x1").should_fail <<EOM
-ERROR: /cookbook_artifacts/x-1x1 cannot be updated: cookbook artifacts are immutable once uploaded.
+ knife("upload /cookbook_artifacts/x-1x1").should_fail <<~EOM
+ ERROR: /cookbook_artifacts/x-1x1 cannot be updated: cookbook artifacts are immutable once uploaded.
EOM
end
end
@@ -1420,20 +1420,20 @@ EOM
end
it "knife upload updates everything" do
- knife("upload /").should_succeed <<EOM
-Updated /acls/groups/blah.json
-Updated /clients/x.json
-Updated /cookbooks/x
-Updated /data_bags/x/y.json
-Updated /environments/x.json
-Updated /groups/x.json
-Updated /invitations.json
-Updated /members.json
-Updated /nodes/x.json
-Updated /org.json
-Created /policies/blah-1.0.0.json
-Updated /policy_groups/x.json
-Updated /roles/x.json
+ knife("upload /").should_succeed <<~EOM
+ Updated /acls/groups/blah.json
+ Updated /clients/x.json
+ Updated /cookbooks/x
+ Updated /data_bags/x/y.json
+ Updated /environments/x.json
+ Updated /groups/x.json
+ Updated /invitations.json
+ Updated /members.json
+ Updated /nodes/x.json
+ Updated /org.json
+ Created /policies/blah-1.0.0.json
+ Updated /policy_groups/x.json
+ Updated /roles/x.json
EOM
knife("diff --name-status --diff-filter=AMT /").should_succeed ""
end
@@ -1472,7 +1472,7 @@ EOM
end
it "knife upload / emits a warning for bar and invites foobar" do
- knife("upload /").should_succeed "Updated /invitations.json\n", :stderr => "WARN: Could not invite bar to organization foo: User bar is already in organization foo\n"
+ knife("upload /").should_succeed "Updated /invitations.json\n", stderr: "WARN: Could not invite bar to organization foo: User bar is already in organization foo\n"
expect(api.get("association_requests").map { |a| a["username"] }).to eq(%w{foo foobar})
expect(api.get("users").map { |a| a["user"]["username"] }).to eq([ "bar" ])
end
diff --git a/spec/integration/recipes/accumulator_spec.rb b/spec/integration/recipes/accumulator_spec.rb
index 4a193bd7f0..65a05fcdc5 100644
--- a/spec/integration/recipes/accumulator_spec.rb
+++ b/spec/integration/recipes/accumulator_spec.rb
@@ -119,7 +119,7 @@ describe "Accumulators" do
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
result.error!
# runs only a single template resource (in the outer run context, as a delayed resource)
expect(result.stdout.scan(/template\S+ action create/).size).to eql(1)
@@ -221,7 +221,7 @@ describe "Accumulators" do
log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
result.error!
# runs only a single template resource (in the outer run context, as a delayed resource)
expect(result.stdout.scan(/template\S+ action create/).size).to eql(1)
diff --git a/spec/integration/recipes/lwrp_inline_resources_spec.rb b/spec/integration/recipes/lwrp_inline_resources_spec.rb
index 54ce94f263..bda4728449 100644
--- a/spec/integration/recipes/lwrp_inline_resources_spec.rb
+++ b/spec/integration/recipes/lwrp_inline_resources_spec.rb
@@ -105,9 +105,9 @@ describe "LWRPs with inline resources" do
r = lwrp_inline_resources_test2 "hi" do
action :b
end
- 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)
+ 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)
expect(r.ran_b).to eq "ran b: ran_a value was \"ran a\""
end
end
@@ -145,13 +145,13 @@ describe "LWRPs with inline resources" do
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
actual = result.stdout.lines.map { |l| l.chomp }.join("\n")
expected = <<EOM
* x_my_machine[me] action create
diff --git a/spec/integration/recipes/lwrp_spec.rb b/spec/integration/recipes/lwrp_spec.rb
index 3bc008d4f8..3f591d4cfc 100644
--- a/spec/integration/recipes/lwrp_spec.rb
+++ b/spec/integration/recipes/lwrp_spec.rb
@@ -22,29 +22,29 @@ describe "LWRPs" do
before do
directory "cookbooks/l-w-r-p" do
- file "resources/foo.rb", <<EOM
-default_action :create
+ file "resources/foo.rb", <<~EOM
+ default_action :create
EOM
- file "providers/foo.rb", <<EOM
-action :create do
-end
+ file "providers/foo.rb", <<~EOM
+ action :create do
+ end
EOM
- file "recipes/default.rb", <<EOM
-l_w_r_p_foo "me"
+ file "recipes/default.rb", <<~EOM
+ l_w_r_p_foo "me"
EOM
end # directory 'cookbooks/x'
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'l-w-r-p::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'l-w-r-p::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* l_w_r_p_foo\[me\] action create \(up to date\)/)
expect(result.stdout).not_to match(/WARN: You are overriding l_w_r_p_foo/)
result.error!
diff --git a/spec/integration/recipes/noop_resource_spec.rb b/spec/integration/recipes/noop_resource_spec.rb
index e0cf47c371..db6b668553 100644
--- a/spec/integration/recipes/noop_resource_spec.rb
+++ b/spec/integration/recipes/noop_resource_spec.rb
@@ -4,7 +4,7 @@ describe "Resources with a no-op provider" do
include IntegrationSupport
context "with noop provider providing foo" do
- before(:context) do
+ before(:each) do
class NoOpFoo < Chef::Resource
resource_name "hi_there"
default_action :update
diff --git a/spec/integration/recipes/notifies_spec.rb b/spec/integration/recipes/notifies_spec.rb
index b008e4ade7..d9e89e7f1e 100644
--- a/spec/integration/recipes/notifies_spec.rb
+++ b/spec/integration/recipes/notifies_spec.rb
@@ -26,13 +26,13 @@ describe "notifications" do
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* apt_update\[\] action nothing \(skipped due to action :nothing\)\s+\* log\[foo\] action write\s+\* log\[bar\] action write\s+\* apt_update\[\] action nothing \(skipped due to action :nothing\)/)
result.error!
@@ -43,37 +43,37 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, 'log[foo]', :delayed
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, 'log[foo]', :delayed
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-notifying_test "whatever"
-log "baz"
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ notifying_test "whatever"
+ log "baz"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
result.error!
@@ -84,39 +84,39 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, 'log[foo]', :delayed
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, 'log[foo]', :delayed
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-notifying_test "whatever"
-log "baz" do
- notifies :write, 'log[foo]', :delayed
-end
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ notifying_test "whatever"
+ log "baz" do
+ notifies :write, 'log[foo]', :delayed
+ end
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# our delayed notification should run at the end of the parent run_context after the baz resource
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
# and only run once
@@ -129,41 +129,41 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, 'log[foo]', :delayed
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, 'log[foo]', :delayed
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-log "quux" do
- notifies :write, 'log[foo]', :delayed
- notifies :write, 'log[baz]', :delayed
-end
-notifying_test "whatever"
-log "baz"
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ log "quux" do
+ notifies :write, 'log[foo]', :delayed
+ notifies :write, 'log[baz]', :delayed
+ end
+ notifying_test "whatever"
+ log "baz"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
expect(result.stdout).to match(/\* log\[quux\] action write\s+\* notifying_test\[whatever\] action run\s+\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
# and only run once
@@ -175,29 +175,29 @@ EOM
when_the_repository "notifies delayed four" do
before do
directory "cookbooks/x" do
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-log "bar" do
- notifies :write, 'log[foo]', :delayed
-end
-log "baz" do
- notifies :write, 'log[foo]', :delayed
-end
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ log "bar" do
+ notifies :write, 'log[foo]', :delayed
+ end
+ log "baz" do
+ notifies :write, 'log[foo]', :delayed
+ end
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
# the delayed notification from the sub-resource is de-duplicated by the notification already in the parent run_context
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[baz\] action write\s+\* log\[foo\] action write/)
# and only run once
@@ -210,37 +210,37 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, 'log[foo]', :immediately
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, 'log[foo]', :immediately
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-notifying_test "whatever"
-log "baz"
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ notifying_test "whatever"
+ log "baz"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
result.error!
end
@@ -250,37 +250,37 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, resources(log: "foo"), :immediately
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, resources(log: "foo"), :immediately
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "foo" do
- action :nothing
-end
-notifying_test "whatever"
-log "baz"
+ file "recipes/default.rb", <<~EOM
+ log "foo" do
+ action :nothing
+ end
+ notifying_test "whatever"
+ log "baz"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[bar\] action write\s+\* log\[foo\] action write\s+\* log\[baz\] action write/)
result.error!
end
@@ -290,34 +290,34 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/notifying_test.rb", <<EOM
-default_action :run
-provides :notifying_test
-resource_name :notifying_test
+ file "resources/notifying_test.rb", <<~EOM
+ default_action :run
+ provides :notifying_test
+ resource_name :notifying_test
-action :run do
- log "bar" do
- notifies :write, "log[foo]"
- end
-end
+ action :run do
+ log "bar" do
+ notifies :write, "log[foo]"
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-notifying_test "whatever"
-log "baz"
+ file "recipes/default.rb", <<~EOM
+ notifying_test "whatever"
+ log "baz"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/Chef::Exceptions::ResourceNotFound/)
expect(result.exitstatus).not_to eql(0)
end
@@ -327,37 +327,37 @@ EOM
before do
directory "cookbooks/x" do
- file "resources/cloning_test.rb", <<EOM
-default_action :run
-provides :cloning_test
-resource_name :cloning_test
+ file "resources/cloning_test.rb", <<~EOM
+ default_action :run
+ provides :cloning_test
+ resource_name :cloning_test
-action :run do
- log "bar" do
- level :info
- end
-end
+ action :run do
+ log "bar" do
+ level :info
+ end
+ end
EOM
- file "recipes/default.rb", <<EOM
-log "bar" do
- level :warn
-end
+ file "recipes/default.rb", <<~EOM
+ log "bar" do
+ level :warn
+ end
-cloning_test "whatever"
+ cloning_test "whatever"
EOM
end
end
it "should complete with success" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).not_to match(/CHEF-3694/)
result.error!
end
@@ -379,13 +379,13 @@ EOM
end
it "notifying the resource should work" do
- file "config/client.rb", <<EOM
-local_mode true
-cookbook_path "#{path_to('cookbooks')}"
-log_level :warn
+ file "config/client.rb", <<~EOM
+ local_mode true
+ cookbook_path "#{path_to('cookbooks')}"
+ log_level :warn
EOM
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match /\* log\[a, b\] action write/
result.error!
end
diff --git a/spec/integration/recipes/notifying_block_spec.rb b/spec/integration/recipes/notifying_block_spec.rb
index 6a1287c7b1..6c50854038 100644
--- a/spec/integration/recipes/notifying_block_spec.rb
+++ b/spec/integration/recipes/notifying_block_spec.rb
@@ -55,7 +55,7 @@ describe "notifying_block" do
# 2. delayed notifications are de-dup'd in the subcontext
# 3. delayed notifications (to resources inside the subcontext) are run at the end of the subcontext
it "should run alpha, beta, gamma, and delta in that order" do
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[alpha\] action write\s+\* log\[beta\] action write\s+\* log\[gamma\] action write\s+Converging 1 resources\s+\* log\[delta\] action write/)
result.error!
end
@@ -103,7 +103,7 @@ describe "notifying_block" do
# 1. notifying block will correctly update wrapping new_resource updated_by_last_action status
# 2. delayed notifications from a subcontext inside a resource will notify resources in their outer run_context
it "should run foo, quux, bar, and baz in that order" do
- result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", :cwd => chef_dir)
+ result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" --no-color -F doc -o 'x::default'", cwd: chef_dir)
expect(result.stdout).to match(/\* log\[foo\] action write\s+\* log\[quux\] action write\s+\* log\[bar\] action write\s+\* log\[baz\] action write/)
result.error!
end
diff --git a/spec/integration/recipes/recipe_dsl_spec.rb b/spec/integration/recipes/recipe_dsl_spec.rb
index f7a0e8b6e8..0250786f0e 100644
--- a/spec/integration/recipes/recipe_dsl_spec.rb
+++ b/spec/integration/recipes/recipe_dsl_spec.rb
@@ -12,7 +12,7 @@ describe "Recipe DSL methods" do
before { Namer.current_index += 1 }
context "with resource 'base_thingy' declared as BaseThingy" do
- before(:context) do
+ before(:each) do
class BaseThingy < Chef::Resource
resource_name "base_thingy"
@@ -66,7 +66,7 @@ describe "Recipe DSL methods" do
end
context "nameless resources" do
- before(:context) do
+ before(:each) do
class NamelessThingy < BaseThingy
resource_name :nameless_thingy
provides :nameless_thingy
@@ -91,7 +91,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named RecipeDSLSpecNamespace::Bar::BarThingy" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Bar::BarThingy < BaseThingy
end
@@ -106,7 +106,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named Chef::Resource::NoNameThingy with resource_name nil" do
- before(:context) do
+ before(:each) do
class Chef::Resource::NoNameThingy < BaseThingy
resource_name nil
@@ -122,7 +122,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy with resource_name :another_thingy_name" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy < BaseThingy
resource_name :another_thingy_name
@@ -146,7 +146,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy2 with resource_name :another_thingy_name2; resource_name :another_thingy_name3" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy2 < BaseThingy
resource_name :another_thingy_name2
@@ -178,7 +178,7 @@ describe "Recipe DSL methods" do
context "provides overriding resource_name" do
context "with a resource named AnotherNoNameThingy3 with provides :another_no_name_thingy3, os: 'blarghle'" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy3 < BaseThingy
resource_name :another_no_name_thingy_3
@@ -207,7 +207,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy4 with two provides" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy4 < BaseThingy
resource_name :another_no_name_thingy_4
@@ -247,7 +247,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy5, a different resource_name, and a provides with the original resource_name" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy5 < BaseThingy
resource_name :another_thingy_name_for_another_no_name_thingy5
@@ -284,7 +284,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy6, a provides with the original resource name, and a different resource_name" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy6 < BaseThingy
provides :another_no_name_thingy6, os: "blarghle"
@@ -321,7 +321,7 @@ describe "Recipe DSL methods" do
end
context "with a resource named AnotherNoNameThingy7, a new resource_name, and provides with that new resource name" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy7 < BaseThingy
resource_name :another_thingy_name_for_another_no_name_thingy7
@@ -359,7 +359,7 @@ describe "Recipe DSL methods" do
# opposite order from the previous test (provides, then resource_name)
context "with a resource named AnotherNoNameThingy8, a provides with a new resource name, and resource_name with that new resource name" do
- before(:context) do
+ before(:each) do
class AnotherNoNameThingy8 < BaseThingy
provides :another_thingy_name_for_another_no_name_thingy8, os: "blarghle"
@@ -399,7 +399,7 @@ describe "Recipe DSL methods" do
context "provides" do
context "when MySupplier provides :hemlock" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::MySupplier < BaseThingy
resource_name :hemlock
@@ -422,7 +422,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy3 has resource_name :thingy3" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy3 < BaseThingy
resource_name :thingy3
@@ -438,7 +438,7 @@ describe "Recipe DSL methods" do
end
context "and Thingy4 has resource_name :thingy3" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy4 < BaseThingy
resource_name :thingy3
@@ -446,11 +446,11 @@ describe "Recipe DSL methods" do
end
- it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do
+ it "thingy3 works in a recipe and yields Thingy4 (the last one)" do
recipe = converge do
thingy3("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4
end
it "thingy4 does not work in a recipe" do
@@ -460,13 +460,13 @@ describe "Recipe DSL methods" do
end
it "resource_matching_short_name returns Thingy4" do
- expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy4
end
end
end
context "when Thingy5 has resource_name :thingy5 and provides :thingy5reverse, :thingy5_2 and :thingy5_2reverse" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy5 < BaseThingy
resource_name :thingy5
@@ -485,7 +485,7 @@ describe "Recipe DSL methods" do
end
context "and Thingy6 provides :thingy5" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy6 < BaseThingy
resource_name :thingy6
@@ -501,19 +501,19 @@ describe "Recipe DSL methods" do
expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy6
end
- it "thingy5 works in a recipe and yields Foo::Thingy5 (the alphabetical one)" do
+ it "thingy5 works in a recipe and yields Foo::Thingy6 (the last one)" do
recipe = converge do
thingy5("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5
+ expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy6
end
- it "resource_matching_short_name returns Thingy5" do
+ it "resource_matching_short_name returns Thingy6" do
expect(Chef::Resource.resource_matching_short_name(:thingy5)).to eq RecipeDSLSpecNamespace::Thingy5
end
context "and AThingy5 provides :thingy5reverse" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::AThingy5 < BaseThingy
resource_name :thingy5reverse
@@ -530,7 +530,7 @@ describe "Recipe DSL methods" do
end
context "and ZRecipeDSLSpecNamespace::Thingy5 provides :thingy5_2" do
- before(:context) do
+ before(:each) do
module ZRecipeDSLSpecNamespace
class Thingy5 < BaseThingy
@@ -540,16 +540,16 @@ describe "Recipe DSL methods" do
end
- it "thingy5_2 works in a recipe and yields the RecipeDSLSpaceNamespace one (the alphabetical one)" do
+ it "thingy5_2 works in a recipe and yields the ZRecipeDSLSpaceNamespace one (the last one)" do
recipe = converge do
thingy5_2("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy5
+ expect(BaseThingy.created_resource).to eq ZRecipeDSLSpecNamespace::Thingy5
end
end
context "and ARecipeDSLSpecNamespace::Thingy5 provides :thingy5_2" do
- before(:context) do
+ before(:each) do
module ARecipeDSLSpecNamespace
class Thingy5 < BaseThingy
@@ -569,7 +569,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy3 has resource_name :thingy3" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy3 < BaseThingy
resource_name :thingy3
@@ -585,7 +585,7 @@ describe "Recipe DSL methods" do
end
context "and Thingy4 has resource_name :thingy3" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy4 < BaseThingy
resource_name :thingy3
@@ -593,11 +593,11 @@ describe "Recipe DSL methods" do
end
- it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do
+ it "thingy3 works in a recipe and yields Thingy4 (the last one)" do
recipe = converge do
thingy3("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4
end
it "thingy4 does not work in a recipe" do
@@ -607,12 +607,12 @@ describe "Recipe DSL methods" do
end
it "resource_matching_short_name returns Thingy4" do
- expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy4
end
end
context "and Thingy4 has resource_name :thingy3" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy4 < BaseThingy
resource_name :thingy3
@@ -620,11 +620,11 @@ describe "Recipe DSL methods" do
end
- it "thingy3 works in a recipe and yields Thingy3 (the alphabetical one)" do
+ it "thingy3 works in a recipe and yields Thingy4 (the last one)" do
recipe = converge do
thingy3("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy4
end
it "thingy4 does not work in a recipe" do
@@ -634,7 +634,7 @@ describe "Recipe DSL methods" do
end
it "resource_matching_short_name returns Thingy4" do
- expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy3
+ expect(Chef::Resource.resource_matching_short_name(:thingy3)).to eq RecipeDSLSpecNamespace::Thingy4
end
end
end
@@ -642,7 +642,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy7 provides :thingy8" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy7 < BaseThingy
resource_name :thingy7
@@ -652,7 +652,7 @@ describe "Recipe DSL methods" do
end
context "and Thingy8 has resource_name :thingy8" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy8 < BaseThingy
resource_name :thingy8
@@ -667,11 +667,11 @@ describe "Recipe DSL methods" do
expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy7
end
- it "thingy8 works in a recipe and yields Thingy7 (alphabetical)" do
+ it "thingy8 works in a recipe and yields Thingy7 (last)" do
recipe = converge do
thingy8("blah") {}
end
- expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy7
+ expect(BaseThingy.created_resource).to eq RecipeDSLSpecNamespace::Thingy8
end
it "resource_matching_short_name returns Thingy8" do
@@ -681,7 +681,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy12 provides :thingy12, :twizzle and :twizzle2" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy12 < BaseThingy
resource_name :thingy12
@@ -714,7 +714,7 @@ describe "Recipe DSL methods" do
end
context "with platform-specific resources 'my_super_thingy_foo' and 'my_super_thingy_bar'" do
- before(:context) do
+ before(:each) do
class MySuperThingyFoo < BaseThingy
resource_name :my_super_thingy_foo
provides :my_super_thingy, platform: "foo"
@@ -760,7 +760,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy10 provides :thingy10" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy10 < BaseThingy
resource_name :thingy10
end
@@ -775,7 +775,7 @@ describe "Recipe DSL methods" do
end
context "when Thingy11 provides :thingy11" do
- before(:context) do
+ before(:each) do
class RecipeDSLSpecNamespace::Thingy11 < BaseThingy
resource_name :thingy10
end
@@ -853,17 +853,17 @@ describe "Recipe DSL methods" do
end
before { resource_class_z } # pull on it so it gets defined before the recipe runs
- it "two_classes_one_dsl resolves to B (alphabetically earliest)" do
+ it "two_classes_one_dsl resolves to Z (last)" do
temp_two_classes_one_dsl = two_classes_one_dsl
recipe = converge do
instance_eval("#{temp_two_classes_one_dsl} 'blah'")
end
expect(recipe.logged_warnings).to eq ""
- expect(BaseThingy.created_resource).to eq resource_class
+ expect(BaseThingy.created_resource).to eq resource_class_z
end
- it "resource_matching_short_name returns B" do
- expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class
+ it "resource_matching_short_name returns Z" do
+ expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class_z
end
context "and a priority array [ Z, B ]" do
@@ -880,8 +880,8 @@ describe "Recipe DSL methods" do
expect(BaseThingy.created_resource).to eq resource_class_z
end
- it "resource_matching_short_name returns B" do
- expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class
+ it "resource_matching_short_name returns Z" do
+ expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class_z
end
context "when Z provides(:two_classes_one_dsl) { false }" do
@@ -919,8 +919,8 @@ describe "Recipe DSL methods" do
expect(BaseThingy.created_resource).to eq resource_class_z
end
- it "resource_matching_short_name returns B" do
- expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class
+ it "resource_matching_short_name returns Z" do
+ expect(Chef::Resource.resource_matching_short_name(two_classes_one_dsl)).to eq resource_class_z
end
context "when Z provides(:two_classes_one_dsl) { false }" do
@@ -1047,13 +1047,13 @@ describe "Recipe DSL methods" do
context "which provides :two_classes_one_dsl" do
before { provider_class_z.provides two_classes_one_dsl }
- it "two_classes_one_dsl resolves to B (alphabetically earliest)" do
+ it "two_classes_one_dsl resolves to Z (last)" do
temp_two_classes_one_dsl = two_classes_one_dsl
recipe = converge do
instance_eval("#{temp_two_classes_one_dsl} 'blah'")
end
expect(recipe.logged_warnings).to eq ""
- expect(BaseThingy.created_provider).to eq provider_class
+ expect(BaseThingy.created_provider).to eq provider_class_z
end
context "with a priority array [ Z, B ]" do
@@ -1309,7 +1309,7 @@ describe "Recipe DSL methods" do
end
context "with UTF-8 provides" do
- before(:context) do
+ before(:each) do
class UTF8Thingy < BaseThingy
resource_name :Straße
provides :Straße
diff --git a/spec/integration/recipes/remote_directory.rb b/spec/integration/recipes/remote_directory.rb
index 77fe183136..a0e3e23ef3 100644
--- a/spec/integration/recipes/remote_directory.rb
+++ b/spec/integration/recipes/remote_directory.rb
@@ -50,7 +50,7 @@ describe Chef::Resource::RemoteDirectory do
end
EOM
end
- shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'test::default'", :cwd => chef_dir)
+ shell_out!("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'test::default'", cwd: chef_dir)
end
def mode_of(path)
diff --git a/spec/integration/recipes/resource_action_spec.rb b/spec/integration/recipes/resource_action_spec.rb
index f5f2d4a764..149b17fcad 100644
--- a/spec/integration/recipes/resource_action_spec.rb
+++ b/spec/integration/recipes/resource_action_spec.rb
@@ -1,5 +1,30 @@
require "support/shared/integration/integration_helper"
+class NoActionJackson < Chef::Resource
+ use_automatic_resource_name
+
+ def foo(value = nil)
+ @foo = value if value
+ @foo
+ end
+
+ class <<self
+ attr_accessor :action_was
+ end
+end
+
+class WeirdActionJackson < Chef::Resource
+ use_automatic_resource_name
+
+ class <<self
+ attr_accessor :action_was
+ end
+
+ action :Straße do
+ WeirdActionJackson.action_was = action
+ end
+end
+
# Houses any classes we declare
module ResourceActionSpec
@@ -229,7 +254,7 @@ module ResourceActionSpec
end
context "And 'action_jackgrandson' inheriting from ActionJackson and changing nothing" do
- before(:context) do
+ before(:each) do
class ActionJackgrandson < ActionJackson
use_automatic_resource_name
end
@@ -333,19 +358,6 @@ module ResourceActionSpec
end
context "With a resource with no actions" do
- class NoActionJackson < Chef::Resource
- use_automatic_resource_name
-
- def foo(value = nil)
- @foo = value if value
- @foo
- end
-
- class <<self
- attr_accessor :action_was
- end
- end
-
it "the default action is :nothing" do
converge do
no_action_jackson "hi" do
@@ -358,18 +370,6 @@ module ResourceActionSpec
end
context "With a resource with a UTF-8 action" do
- class WeirdActionJackson < Chef::Resource
- use_automatic_resource_name
-
- class <<self
- attr_accessor :action_was
- end
-
- action :Straße do
- WeirdActionJackson.action_was = action
- end
- end
-
it "Running the action works" do
expect_recipe do
weird_action_jackson "hi"
@@ -378,94 +378,6 @@ module ResourceActionSpec
end
end
- context "With a resource with property x" do
- class ResourceActionSpecWithX < Chef::Resource
- resource_name :resource_action_spec_with_x
- property :x, default: 20
- action :set do
- # Access x during converge to ensure that we emit no warnings there
- x
- end
- end
-
- context "And another resource with a property x and an action that sets property x to its value" do
- class ResourceActionSpecAlsoWithX < Chef::Resource
- resource_name :resource_action_spec_also_with_x
- property :x
- action :set_x_to_x do
- resource_action_spec_with_x "hi" do
- x x
- end
- end
- def self.x_warning_line
- __LINE__ - 4
- end
- action :set_x_to_x_in_non_initializer do
- r = resource_action_spec_with_x "hi" do
- x 10
- end
- x_times_2 = r.x * 2
- end
- action :set_x_to_10 do
- resource_action_spec_with_x "hi" do
- x 10
- end
- end
- end
-
- attr_reader :x_warning_line
-
- it "Using the enclosing resource to set x to x emits a warning that you're using the wrong x" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- recipe = converge do
- resource_action_spec_also_with_x "hi" do
- x 1
- action :set_x_to_x
- end
- end
- warnings = recipe.logs.lines.select { |l| l =~ /warn/i }
- expect(warnings.size).to eq 2
- expect(warnings[0]).to match(/property x is declared in both resource_action_spec_with_x\[hi\] and resource_action_spec_also_with_x\[hi\] action :set_x_to_x. Use new_resource.x instead. At #{__FILE__}:#{ResourceActionSpecAlsoWithX.x_warning_line}/)
- end
-
- it "Using the enclosing resource to set x to x outside the initializer emits no warning" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- recipe = converge do
- resource_action_spec_also_with_x "hi" do
- x 1
- action :set_x_to_x_in_non_initializer
- end
- end
- warnings = recipe.logs.lines.select { |l| l =~ /warn/i }
- expect(warnings.size).to eq 1 # the deprecation warning, not the property masking one
- end
-
- it "Using the enclosing resource to set x to 10 emits no warning" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- recipe = converge do
- resource_action_spec_also_with_x "hi" do
- x 1
- action :set_x_to_10
- end
- end
- warnings = recipe.logs.lines.select { |l| l =~ /warn/i }
- expect(warnings.size).to eq 1 # the deprecation warning, not the property masking one
- end
-
- it "Using the enclosing resource to set x to 10 emits no warning" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- recipe = converge do
- r = resource_action_spec_also_with_x "hi"
- r.x 1
- r.action :set_x_to_10
- end
- warnings = recipe.logs.lines.select { |l| l =~ /warn/i }
- expect(warnings.size).to eq 1 # the deprecation warning, not the property masking one
- end
- end
-
- end
-
context "With a resource with a set_or_return property named group (same name as a resource)" do
class ResourceActionSpecWithGroupAction < Chef::Resource
resource_name :resource_action_spec_set_group_to_nil
@@ -504,13 +416,6 @@ module ResourceActionSpec
end
end
end
-
- it "Raises an error when attempting to use a template in the action" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- expect_converge do
- has_property_named_template "hi"
- end.to raise_error(/Property `template` of `has_property_named_template\[hi\]` was incorrectly passed a block. Possible property-resource collision. To call a resource named `template` either rename the property or else use `declare_resource\(:template, ...\)`/)
- end
end
context "When a resource declares methods in action_class" do
diff --git a/spec/integration/recipes/resource_converge_if_changed_spec.rb b/spec/integration/recipes/resource_converge_if_changed_spec.rb
index 89d831ddec..e1def5e191 100644
--- a/spec/integration/recipes/resource_converge_if_changed_spec.rb
+++ b/spec/integration/recipes/resource_converge_if_changed_spec.rb
@@ -17,7 +17,7 @@ describe "Resource::ActionClass#converge_if_changed" do
before { Namer.current_index += 1 }
before { Namer.incrementing_value = 0 }
- context "when the resource has identity, state and control properties" do
+ context "when the resource has identity, state, control, and sensitive properties" do
let(:resource_name) { :"converge_if_changed_dsl#{Namer.current_index}" }
let(:resource_class) do
result = Class.new(Chef::Resource) do
@@ -28,6 +28,7 @@ describe "Resource::ActionClass#converge_if_changed" do
property :control1, desired_state: false, default: "default_control1"
property :state1, default: "default_state1"
property :state2, default: "default_state2"
+ property :sensitive1, default: "default_dontprintme", sensitive: true
attr_accessor :converged
def initialize(*args)
super
@@ -54,6 +55,7 @@ describe "Resource::ActionClass#converge_if_changed" do
resource_class.load_current_value do
state1 "current_state1"
state2 "current_state2"
+ sensitive1 "current_dontprintme"
end
end
@@ -63,8 +65,8 @@ describe "Resource::ActionClass#converge_if_changed" do
it "the resource updates nothing" do
expect(resource.converged).to eq 0
expect(resource.updated?).to be_falsey
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create (up to date)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create (up to date)
EOM
end
end
@@ -81,10 +83,10 @@ describe "Resource::ActionClass#converge_if_changed" do
it "the resource updates state1" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state1 to "new_state1" (was "current_state1")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state1 to "new_state1" (was "current_state1")
EOM
end
end
@@ -102,11 +104,11 @@ describe "Resource::ActionClass#converge_if_changed" do
it "the resource updates state1 and state2" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state1 to "new_state1" (was "current_state1")
- - set state2 to "new_state2" (was "current_state2")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state1 to "new_state1" (was "current_state1")
+ - set state2 to "new_state2" (was "current_state2")
EOM
end
end
@@ -125,11 +127,31 @@ EOM
it "the resource updates state1 and state2" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state1 to (suppressed sensitive property)
- - set state2 to (suppressed sensitive property)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state1 to (suppressed sensitive property)
+ - set state2 to (suppressed sensitive property)
+EOM
+ end
+ end
+
+ context "and sensitive1 is set to a new value" do
+ let(:converge_recipe) do
+ <<-EOM
+ #{resource_name} 'blah' do
+ sensitive1 'new_dontprintme'
+ end
+ EOM
+ end
+
+ it "the resource updates sensitive1" do
+ expect(resource.converged).to eq 1
+ expect(resource.updated?).to be_truthy
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set sensitive1 to (suppressed sensitive property)
EOM
end
end
@@ -147,10 +169,10 @@ EOM
it "the resource updates state2" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state2 to "new_state2" (was "current_state2")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state2 to "new_state2" (was "current_state2")
EOM
end
end
@@ -168,8 +190,8 @@ EOM
it "the resource updates nothing" do
expect(resource.converged).to eq 0
expect(resource.updated?).to be_falsey
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create (up to date)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create (up to date)
EOM
end
end
@@ -189,8 +211,8 @@ EOM
it "the resource updates nothing" do
expect(resource.converged).to eq 0
expect(resource.updated?).to be_falsey
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create (up to date)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create (up to date)
EOM
end
end
@@ -219,10 +241,10 @@ EOM
it "the resource updates identity1" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update current_identity1
- - set identity1 to "new_identity1" (was "current_identity1")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update current_identity1
+ - set identity1 to "new_identity1" (was "current_identity1")
EOM
end
end
@@ -241,22 +263,24 @@ EOM
it "the resource is created" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set identity1 to "default_identity1" (default value)
- - set state1 to "default_state1" (default value)
- - set state2 to "default_state2" (default value)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set identity1 to "default_identity1" (default value)
+ - set state1 to "default_state1" (default value)
+ - set state2 to "default_state2" (default value)
+ - set sensitive1 to (suppressed sensitive property) (default value)
EOM
end
end
- context "and state1 and state2 are set" do
+ context "and state1, state2, and sensitive1 are set" do
let(:converge_recipe) do
<<-EOM
#{resource_name} 'blah' do
state1 'new_state1'
state2 'new_state2'
+ sensitive1 'new_dontprintme'
end
EOM
end
@@ -264,12 +288,13 @@ EOM
it "the resource is created" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set identity1 to "default_identity1" (default value)
- - set state1 to "new_state1"
- - set state2 to "new_state2"
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set identity1 to "default_identity1" (default value)
+ - set state1 to "new_state1"
+ - set state2 to "new_state2"
+ - set sensitive1 to (suppressed sensitive property)
EOM
end
end
@@ -288,12 +313,13 @@ EOM
it "the resource is created" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set identity1 to (suppressed sensitive property) (default value)
- - set state1 to (suppressed sensitive property)
- - set state2 to (suppressed sensitive property)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set identity1 to (suppressed sensitive property) (default value)
+ - set state1 to (suppressed sensitive property)
+ - set state2 to (suppressed sensitive property)
+ - set sensitive1 to (suppressed sensitive property) (default value)
EOM
end
end
@@ -309,6 +335,9 @@ EOM
converge_if_changed :state2 do
new_resource.converged += 1
end
+ converge_if_changed :sensitive1 do
+ new_resource.converged += 1
+ end
end
end
@@ -326,8 +355,8 @@ EOM
it "the resource updates nothing" do
expect(resource.converged).to eq 0
expect(resource.updated?).to be_falsey
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create (up to date)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create (up to date)
EOM
end
end
@@ -345,10 +374,10 @@ EOM
it "the resource updates state1" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state1 to "new_state1" (was "current_state1")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state1 to "new_state1" (was "current_state1")
EOM
end
end
@@ -366,12 +395,12 @@ EOM
it "the resource updates state1 and state2" do
expect(resource.converged).to eq 2
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state1 to "new_state1" (was "current_state1")
- - update default_identity1
- - set state2 to "new_state2" (was "current_state2")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state1 to "new_state1" (was "current_state1")
+ - update default_identity1
+ - set state2 to "new_state2" (was "current_state2")
EOM
end
end
@@ -389,10 +418,10 @@ EOM
it "the resource updates state2" do
expect(resource.converged).to eq 1
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - update default_identity1
- - set state2 to "new_state2" (was "current_state2")
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set state2 to "new_state2" (was "current_state2")
EOM
end
end
@@ -410,8 +439,28 @@ EOM
it "the resource updates nothing" do
expect(resource.converged).to eq 0
expect(resource.updated?).to be_falsey
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create (up to date)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create (up to date)
+EOM
+ end
+ end
+
+ context "and sensitive1 is set to a new value" do
+ let(:converge_recipe) do
+ <<-EOM
+ #{resource_name} 'blah' do
+ sensitive1 'new_dontprintme'
+ end
+ EOM
+ end
+
+ it "the resource updates sensitive1" do
+ expect(resource.converged).to eq 1
+ expect(resource.updated?).to be_truthy
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - update default_identity1
+ - set sensitive1 to (suppressed sensitive property)
EOM
end
end
@@ -430,37 +479,42 @@ EOM
end
it "the resource is created" do
- expect(resource.converged).to eq 2
+ expect(resource.converged).to eq 3
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set state1 to "default_state1" (default value)
- - create default_identity1
- - set state2 to "default_state2" (default value)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set state1 to "default_state1" (default value)
+ - create default_identity1
+ - set state2 to "default_state2" (default value)
+ - create default_identity1
+ - set sensitive1 to (suppressed sensitive property) (default value)
EOM
end
end
- context "and state1 and state2 are set to new values" do
+ context "and state1, state2, and sensitive1 are set to new values" do
let(:converge_recipe) do
<<-EOM
#{resource_name} 'blah' do
state1 'new_state1'
state2 'new_state2'
+ sensitive1 'new_dontprintme'
end
EOM
end
it "the resource is created" do
- expect(resource.converged).to eq 2
+ expect(resource.converged).to eq 3
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set state1 to "new_state1"
- - create default_identity1
- - set state2 to "new_state2"
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set state1 to "new_state1"
+ - create default_identity1
+ - set state2 to "new_state2"
+ - create default_identity1
+ - set sensitive1 to (suppressed sensitive property)
EOM
end
end
@@ -477,14 +531,16 @@ EOM
end
it "the resource is created" do
- expect(resource.converged).to eq 2
+ expect(resource.converged).to eq 3
expect(resource.updated?).to be_truthy
- expect(converged_recipe.stdout).to eq <<-EOM
-* #{resource_name}[blah] action create
- - create default_identity1
- - set state1 to (suppressed sensitive property)
- - create default_identity1
- - set state2 to (suppressed sensitive property)
+ expect(converged_recipe.stdout).to eq <<~EOM
+ * #{resource_name}[blah] action create
+ - create default_identity1
+ - set state1 to (suppressed sensitive property)
+ - create default_identity1
+ - set state2 to (suppressed sensitive property)
+ - create default_identity1
+ - set sensitive1 to (suppressed sensitive property) (default value)
EOM
end
end
diff --git a/spec/integration/recipes/resource_load_spec.rb b/spec/integration/recipes/resource_load_spec.rb
index 4fc14c0687..79df1d6478 100644
--- a/spec/integration/recipes/resource_load_spec.rb
+++ b/spec/integration/recipes/resource_load_spec.rb
@@ -156,10 +156,10 @@ describe "Resource.load_current_value" do
context "And a child resource class with load_current_value" do
before do
subresource_class.load_current_value do
- y "loaded_y #{Namer.incrementing_value} (#{self.class.properties.sort_by { |name, p| name }.
- select { |name, p| p.is_set?(self) }.
- map { |name, p| "#{name}=#{p.get(self)}" }.
- join(", ")})"
+ y "loaded_y #{Namer.incrementing_value} (#{self.class.properties.sort_by { |name, p| name }
+ .select { |name, p| p.is_set?(self) }
+ .map { |name, p| "#{name}=#{p.get(self)}" }
+ .join(", ")})"
end
end
@@ -174,10 +174,10 @@ describe "Resource.load_current_value" do
before do
subresource_class.load_current_value do
super()
- y "loaded_y #{Namer.incrementing_value} (#{self.class.properties.sort_by { |name, p| name }.
- select { |name, p| p.is_set?(self) }.
- map { |name, p| "#{name}=#{p.get(self)}" }.
- join(", ")})"
+ y "loaded_y #{Namer.incrementing_value} (#{self.class.properties.sort_by { |name, p| name }
+ .select { |name, p| p.is_set?(self) }
+ .map { |name, p| "#{name}=#{p.get(self)}" }
+ .join(", ")})"
end
end
diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb
index f6cb2e43ef..58314473e7 100644
--- a/spec/integration/solo/solo_spec.rb
+++ b/spec/integration/solo/solo_spec.rb
@@ -23,23 +23,23 @@ describe "chef-solo" do
let(:node_file) { Dir[File.join(nodes_dir, "*.json")][0] }
before do
- file "config/solo.rb", <<EOM
-chef_repo_path "#{@repository_dir}"
+ file "config/solo.rb", <<~EOM
+ chef_repo_path "#{@repository_dir}"
EOM
- result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -l debug", :cwd => chef_dir)
+ result = shell_out("ruby bin/chef-solo -c \"#{path_to('config/solo.rb')}\" -l debug", cwd: chef_dir)
result.error!
end
describe "on unix", :unix_only do
describe "the nodes directory" do
it "has the correct permissions" do
- expect(File.stat(nodes_dir).mode.to_s(8)[2..5]).to eq("700")
+ expect(File.stat(nodes_dir).mode.to_s(8)[-3..-1]).to eq("700")
end
end
describe "the node file" do
it "has the correct permissions" do
- expect(File.stat(node_file).mode.to_s(8)[2..5]).to eq("0600")
+ expect(File.stat(node_file).mode.to_s(8)[-4..-1]).to eq("0600")
end
end
end
@@ -74,26 +74,26 @@ EOM
end
it "should complete with success" do
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
result.error!
expect(result.stdout).to include("ITWORKS")
end
it "should evaluate its node.json file" do
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
- file "config/node.json", <<-E
-{"run_list":["x::default"]}
+ file "config/node.json", <<~E
+ {"run_list":["x::default"]}
E
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -j '#{path_to('config/node.json')}' -l debug", :cwd => chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -j '#{path_to('config/node.json')}' -l debug", cwd: chef_dir)
result.error!
expect(result.stdout).to include("ITWORKS")
end
@@ -110,11 +110,11 @@ E
end
it "should exit with an error" do
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(0) # For CHEF-5120 this becomes 1
expect(result.stdout).to include("WARN: MissingCookbookDependency")
end
@@ -124,14 +124,14 @@ EOM
before do
file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\nchef_version '~> 999.0'")
file "cookbooks/x/recipes/default.rb", 'puts "ITWORKS"'
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
end
it "should exit with an error" do
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(1)
expect(result.stdout).to include("Chef::Exceptions::CookbookChefVersionMismatch")
end
@@ -141,14 +141,14 @@ EOM
before do
file "cookbooks/x/metadata.rb", cb_metadata("x", "1.0.0", "\nohai_version '~> 999.0'")
file "cookbooks/x/recipes/default.rb", 'puts "ITWORKS"'
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
end
it "should exit with an error" do
- result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", :cwd => chef_dir)
+ result = shell_out("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug", cwd: chef_dir)
expect(result.exitstatus).to eq(1)
expect(result.stdout).to include("Chef::Exceptions::CookbookOhaiVersionMismatch")
end
@@ -159,23 +159,23 @@ EOM
directory "logs"
file "logs/runs.log", ""
file "cookbooks/x/metadata.rb", cookbook_x_100_metadata_rb
- file "cookbooks/x/recipes/default.rb", <<EOM
-ruby_block "sleeping" do
- block do
- retries = 200
- while IO.read(Chef::Config[:log_location]) !~ /Chef client .* is running, will wait for it to finish and then run./
- sleep 0.1
- raise "we ran out of retries" if ( retries -= 1 ) <= 0
- end
- end
-end
+ file "cookbooks/x/recipes/default.rb", <<~EOM
+ ruby_block "sleeping" do
+ block do
+ retries = 200
+ while IO.read(Chef::Config[:log_location]) !~ /Chef client .* is running, will wait for it to finish and then run./
+ sleep 0.1
+ raise "we ran out of retries" if ( retries -= 1 ) <= 0
+ end
+ end
+ end
EOM
end
it "while running solo concurrently" do
- file "config/solo.rb", <<EOM
-cookbook_path "#{path_to('cookbooks')}"
-file_cache_path "#{path_to('config/cache')}"
+ file "config/solo.rb", <<~EOM
+ cookbook_path "#{path_to('cookbooks')}"
+ file_cache_path "#{path_to('config/cache')}"
EOM
# We have a timeout protection here so that if due to some bug
# run_lock gets stuck we can discover it.
@@ -187,13 +187,13 @@ EOM
# Instantiate the first chef-solo run
threads << Thread.new do
- s1 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", :chdir => chef_dir)
+ s1 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", chdir: chef_dir)
Process.waitpid(s1)
end
# Instantiate the second chef-solo run
threads << Thread.new do
- s2 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", :chdir => chef_dir)
+ s2 = Process.spawn("#{chef_solo} -c \"#{path_to('config/solo.rb')}\" -o 'x::default' -l debug -L #{path_to('logs/runs.log')}", chdir: chef_dir)
Process.waitpid(s2)
end
diff --git a/spec/scripts/ssl-serve.rb b/spec/scripts/ssl-serve.rb
index 3f4e343926..66e400b6d0 100644
--- a/spec/scripts/ssl-serve.rb
+++ b/spec/scripts/ssl-serve.rb
@@ -20,26 +20,26 @@ 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 = {
- :server => "webrick",
- :Port => 9000,
- :Host => "localhost",
- :environment => :none,
- :Logger => LOGGER,
- :DocumentRoot => File.expand_path("#{Dir.tmpdir}/chef-118-sampledata")
+ server: "webrick",
+ Port: 9000,
+ Host: "localhost",
+ environment: :none,
+ Logger: LOGGER,
+ DocumentRoot: File.expand_path("#{Dir.tmpdir}/chef-118-sampledata")
#:AccessLog => [] # Remove this option to enable the access log when debugging.
-}
+}.freeze
webrick_opts = DEFAULT_OPTIONS.merge(server_opts)
-pp :webrick_opts => webrick_opts
+pp webrick_opts: webrick_opts
server = WEBrick::HTTPServer.new(webrick_opts)
trap("INT") { server.shutdown }
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index bace94fcbe..d900fc2f37 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -50,10 +50,10 @@ end
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 }
+Dir["lib/chef/knife/**/*.rb"]
+ .map { |f| f.gsub("lib/", "") }
+ .map { |f| f.gsub(%r{\.rb$}, "") }
+ .each { |f| require f }
require "chef/resource_resolver"
require "chef/provider_resolver"
@@ -90,12 +90,12 @@ require "spec/support/shared/unit/mock_shellout"
# Autoloads support files
# Excludes support/platforms by default
# Do not change the gsub.
-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/}, "") }.
- each { |f| require f }
+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/}, "") }
+ .each { |f| require f }
OHAI_SYSTEM = Ohai::System.new
OHAI_SYSTEM.all_plugins(["platform", "hostname", "languages/powershell"])
@@ -111,11 +111,16 @@ TEST_PLATFORM = TEST_NODE["platform"]
TEST_PLATFORM_VERSION = TEST_NODE["platform_version"]
TEST_PLATFORM_FAMILY = TEST_NODE["platform_family"]
+provider_priority_map ||= nil
+resource_priority_map ||= nil
+provider_handler_map ||= nil
+resource_handler_map ||= nil
+
RSpec.configure do |config|
config.include(Matchers)
config.include(MockShellout::RSpec)
- config.filter_run :focus => true
- config.filter_run_excluding :external => true
+ config.filter_run focus: true
+ config.filter_run_excluding external: true
# Explicitly disable :should syntax
config.expect_with :rspec do |c|
@@ -129,74 +134,83 @@ RSpec.configure do |config|
config.filter_run_excluding :workstation if solaris? || aix?
# Tests that randomly fail, but may have value.
- config.filter_run_excluding :volatile => true
- config.filter_run_excluding :volatile_on_solaris => true if solaris?
- config.filter_run_excluding :volatile_from_verify => false
-
- config.filter_run_excluding :skip_appveyor => true if ENV["APPVEYOR"]
- config.filter_run_excluding :appveyor_only => true unless ENV["APPVEYOR"]
- config.filter_run_excluding :skip_travis => true if ENV["TRAVIS"]
-
- 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_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?
- config.filter_run_excluding :not_supported_on_nano => true if windows_nano_server?
- config.filter_run_excluding :win2k3_only => true unless windows_win2k3?
- config.filter_run_excluding :win2012r2_only => true unless windows_2012r2?
- config.filter_run_excluding :windows_2008r2_or_later => true unless windows_2008r2_or_later?
- config.filter_run_excluding :windows64_only => true unless windows64?
- config.filter_run_excluding :windows32_only => true unless windows32?
- config.filter_run_excluding :windows_nano_only => true unless windows_nano_server?
- config.filter_run_excluding :windows_gte_10 => true unless windows_gte_10?
- config.filter_run_excluding :windows_lt_10 => true if windows_gte_10?
- config.filter_run_excluding :ruby64_only => true unless ruby_64bit?
- config.filter_run_excluding :ruby32_only => true unless ruby_32bit?
- config.filter_run_excluding :windows_powershell_dsc_only => true unless windows_powershell_dsc?
- config.filter_run_excluding :windows_powershell_no_dsc_only => true unless ! windows_powershell_dsc?
- config.filter_run_excluding :windows_domain_joined_only => true unless windows_domain_joined?
- config.filter_run_excluding :windows_not_domain_joined_only => true if windows_domain_joined?
+ config.filter_run_excluding volatile: true
+ config.filter_run_excluding volatile_on_solaris: true if solaris?
+ config.filter_run_excluding volatile_from_verify: false
+
+ config.filter_run_excluding skip_appveyor: true if ENV["APPVEYOR"]
+ config.filter_run_excluding appveyor_only: true unless ENV["APPVEYOR"]
+ config.filter_run_excluding skip_travis: true if ENV["TRAVIS"]
+
+ 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_aix: true if aix?
+ config.filter_run_excluding not_supported_on_solaris: true if solaris?
+ config.filter_run_excluding not_supported_on_gce: true if gce?
+ config.filter_run_excluding not_supported_on_nano: true if windows_nano_server?
+ config.filter_run_excluding win2012r2_only: true unless windows_2012r2?
+ config.filter_run_excluding windows_2008r2_or_later: true unless windows_2008r2_or_later?
+ config.filter_run_excluding windows64_only: true unless windows64?
+ config.filter_run_excluding windows32_only: true unless windows32?
+ config.filter_run_excluding windows_nano_only: true unless windows_nano_server?
+ config.filter_run_excluding windows_gte_10: true unless windows_gte_10?
+ config.filter_run_excluding windows_lt_10: true if windows_gte_10?
+ config.filter_run_excluding ruby64_only: true unless ruby_64bit?
+ config.filter_run_excluding ruby32_only: true unless ruby_32bit?
+ config.filter_run_excluding windows_powershell_dsc_only: true unless windows_powershell_dsc?
+ config.filter_run_excluding windows_powershell_no_dsc_only: true unless ! windows_powershell_dsc?
+ config.filter_run_excluding windows_domain_joined_only: true unless windows_domain_joined?
+ config.filter_run_excluding windows_not_domain_joined_only: true if windows_domain_joined?
# We think this line was causing rspec tests to not run on the Jenkins windows
# testers. If we ever fix it we should restore it.
# config.filter_run_excluding :windows_service_requires_assign_token => true if !STDOUT.isatty && !windows_user_right?("SeAssignPrimaryTokenPrivilege")
- config.filter_run_excluding :windows_service_requires_assign_token => true
- config.filter_run_excluding :solaris_only => true unless solaris?
- config.filter_run_excluding :system_windows_service_gem_only => true unless system_windows_service_gem?
- config.filter_run_excluding :unix_only => true unless unix?
- config.filter_run_excluding :linux_only => true unless linux?
- config.filter_run_excluding :aix_only => true unless aix?
- config.filter_run_excluding :debian_family_only => true unless debian_family?
- config.filter_run_excluding :supports_cloexec => true unless supports_cloexec?
- config.filter_run_excluding :selinux_only => true unless selinux_enabled?
- config.filter_run_excluding :requires_root => true unless root?
- config.filter_run_excluding :requires_root_or_running_windows => true unless root? || windows?
- config.filter_run_excluding :requires_unprivileged_user => true if root?
- config.filter_run_excluding :uses_diff => true unless has_diff?
- config.filter_run_excluding :openssl_gte_101 => true unless openssl_gte_101?
- config.filter_run_excluding :openssl_lt_101 => true unless openssl_lt_101?
- config.filter_run_excluding :aes_256_gcm_only => true unless aes_256_gcm?
- config.filter_run_excluding :broken => true
- config.filter_run_excluding :not_wpar => true unless wpar?
- config.filter_run_excluding :not_supported_under_fips => true if fips?
+ config.filter_run_excluding windows_service_requires_assign_token: true
+ config.filter_run_excluding solaris_only: true unless solaris?
+ config.filter_run_excluding system_windows_service_gem_only: true unless system_windows_service_gem?
+ config.filter_run_excluding unix_only: true unless unix?
+ config.filter_run_excluding linux_only: true unless linux?
+ config.filter_run_excluding aix_only: true unless aix?
+ config.filter_run_excluding debian_family_only: true unless debian_family?
+ config.filter_run_excluding supports_cloexec: true unless supports_cloexec?
+ config.filter_run_excluding selinux_only: true unless selinux_enabled?
+ config.filter_run_excluding requires_root: true unless root?
+ config.filter_run_excluding requires_root_or_running_windows: true unless root? || windows?
+ config.filter_run_excluding requires_unprivileged_user: true if root?
+ config.filter_run_excluding uses_diff: true unless has_diff?
+ config.filter_run_excluding openssl_gte_101: true unless openssl_gte_101?
+ config.filter_run_excluding openssl_lt_101: true unless openssl_lt_101?
+ config.filter_run_excluding aes_256_gcm_only: true unless aes_256_gcm?
+ config.filter_run_excluding broken: true
+ config.filter_run_excluding not_wpar: true unless wpar?
+ config.filter_run_excluding not_supported_under_fips: true if fips?
+ config.filter_run_excluding rhel: true unless rhel?
+ config.filter_run_excluding rhel5: true unless rhel5?
+ config.filter_run_excluding rhel6: true unless rhel6?
+ config.filter_run_excluding rhel7: true unless rhel7?
+ config.filter_run_excluding intel_64bit: true unless intel_64bit?
+ config.filter_run_excluding not_rhel: true if rhel?
+ config.filter_run_excluding not_rhel5: true if rhel5?
+ config.filter_run_excluding not_rhel6: true if rhel6?
+ config.filter_run_excluding not_rhel7: true if rhel7?
+ config.filter_run_excluding not_intel_64bit: true if intel_64bit?
# these let us use chef: ">= 13" or ruby: "~> 2.0.0" or any other Gem::Dependency-style constraint
config.filter_run_excluding chef: DependencyProc.with(Chef::VERSION)
config.filter_run_excluding ruby: DependencyProc.with(RUBY_VERSION)
- config.filter_run_excluding :choco_installed => true unless choco_installed?
+ config.filter_run_excluding choco_installed: true unless choco_installed?
running_platform_arch = `uname -m`.strip unless windows?
- config.filter_run_excluding :arch => lambda { |target_arch|
+ config.filter_run_excluding arch: lambda { |target_arch|
running_platform_arch != target_arch
}
# Functional Resource tests that are provider-specific:
# context "on platforms that use useradd", :provider => {:user => Chef::Provider::User::Useradd}} do #...
- config.filter_run_excluding :provider => lambda { |criteria|
+ config.filter_run_excluding provider: lambda { |criteria|
type, target_provider = criteria.first
node = TEST_NODE.dup
@@ -233,6 +247,38 @@ RSpec.configure do |config|
# Set environment variable so the setting persists in child processes
ENV["CHEF_TREAT_DEPRECATION_WARNINGS_AS_ERRORS"] = "1"
+
+ # we don't perfectly reset the priority/handler maps here, but by dup'ing the top level hash we
+ # throw away all the garbage resources and providers that we setup. if we mutate something like
+ # :package then that'll carry over from test-to-test, but the solution would be to deep-dup on every
+ # single test we run which is much more expensive. by throwing away the garbage top level keys we
+ # significantly speed up test runs.
+ provider_handler_map ||= Chef.provider_handler_map.send(:map).dup
+ resource_handler_map ||= Chef.resource_handler_map.send(:map).dup
+ provider_priority_map ||= Chef.provider_priority_map.send(:map).dup
+ resource_priority_map ||= Chef.resource_priority_map.send(:map).dup
+ Chef.provider_handler_map.instance_variable_set(:@map, provider_handler_map.dup)
+ Chef.resource_handler_map.instance_variable_set(:@map, resource_handler_map.dup)
+ Chef.provider_priority_map.instance_variable_set(:@map, provider_priority_map.dup)
+ Chef.resource_priority_map.instance_variable_set(:@map, resource_priority_map.dup)
+ end
+
+ # This bit of jankiness guards against specs which accidentally drop privs when running as
+ # root -- which are nearly impossible to debug and so we bail out very hard if this
+ # condition ever happens. If a spec stubs Process.[e]uid this can throw a false positive
+ # which the spec must work around by unmocking Process.[e]uid to and_call_original in its
+ # after block.
+ if Process.euid == 0 && Process.uid == 0
+ config.after(:each) do
+ if Process.uid != 0
+ RSpec.configure { |c| c.fail_fast = true }
+ raise "rspec was invoked as root, but the last test dropped real uid to #{Process.uid}"
+ end
+ if Process.euid != 0
+ RSpec.configure { |c| c.fail_fast = true }
+ raise "rspec was invoked as root, but the last test dropped effective uid to #{Process.euid}"
+ end
+ end
end
# raise if anyone commits any test to CI with :focus set on it
diff --git a/spec/stress/win32/file_spec.rb b/spec/stress/win32/file_spec.rb
index f1c81eb9c6..49dd8694f5 100644
--- a/spec/stress/win32/file_spec.rb
+++ b/spec/stress/win32/file_spec.rb
@@ -26,12 +26,12 @@ describe "Chef::ReservedNames::Win32::File", :windows_only do
it "should not leak significant memory", :volatile do
test = lambda { Chef::ReservedNames::Win32::File.symlink?(@path) }
- expect(test).not_to leak_memory(:warmup => 50000, :iterations => 50000)
+ expect(test).not_to leak_memory(warmup: 50000, iterations: 50000)
end
it "should not leak handles", :volatile do
test = lambda { Chef::ReservedNames::Win32::File.symlink?(@path) }
- expect(test).not_to leak_handles(:warmup => 50, :iterations => 100)
+ 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 3c03a657b2..0280398ad5 100644
--- a/spec/stress/win32/security_spec.rb
+++ b/spec/stress/win32/security_spec.rb
@@ -52,7 +52,7 @@ describe "Chef::ReservedNames::Win32::Security", :windows_only do
expect do
sids = Chef::ReservedNames::Win32::Security::SecurableObject.new(@monkeyfoo).security_descriptor.dacl.select { |ace| ace.sid }
GC.start
- end.not_to leak_memory(:warmup => 50, :iterations => 100)
+ end.not_to leak_memory(warmup: 50, iterations: 100)
end
it "should not leak when creating a new ACL and setting it on a file", :volatile do
@@ -63,7 +63,7 @@ describe "Chef::ReservedNames::Win32::Security", :windows_only do
Chef::ReservedNames::Win32::Security::ACE.access_denied(Chef::ReservedNames::Win32::Security::SID.from_account("Users"), Chef::ReservedNames::Win32::API::Security::GENERIC_ALL),
])
GC.start
- end.not_to leak_memory(:warmup => 50, :iterations => 100)
+ end.not_to leak_memory(warmup: 50, iterations: 100)
end
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 ef03a1133e..4dcbf1e60b 100644
--- a/spec/support/lib/chef/resource/one_two_three_four.rb
+++ b/spec/support/lib/chef/resource/one_two_three_four.rb
@@ -21,8 +21,6 @@ class Chef
class OneTwoThreeFour < Chef::Resource
provides :one_two_three_four
- attr_reader :i_can_count
-
def i_can_count(tf)
@i_can_count = tf
end
diff --git a/spec/support/lib/chef/resource/zen_master.rb b/spec/support/lib/chef/resource/zen_master.rb
index 99d761c8cf..9d6e5d46f7 100644
--- a/spec/support/lib/chef/resource/zen_master.rb
+++ b/spec/support/lib/chef/resource/zen_master.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,8 +25,6 @@ class Chef
provides :zen_master
allowed_actions :win, :score
- attr_reader :peace
-
def peace(tf)
@peace = tf
end
diff --git a/spec/support/mock/constant.rb b/spec/support/mock/constant.rb
index 3a23b4d8d8..7acd02e9d7 100644
--- a/spec/support/mock/constant.rb
+++ b/spec/support/mock/constant.rb
@@ -15,7 +15,7 @@ def mock_constants(constants)
begin
yield
ensure
- constants.each do |constant, val|
+ constants.each_key do |constant|
source_object, const_name = parse_constant(constant)
with_warnings(nil) { source_object.const_set(const_name, saved_constants[constant]) }
end
diff --git a/spec/support/platform_helpers.rb b/spec/support/platform_helpers.rb
index 3cc8778f7a..6ae052ba1d 100644
--- a/spec/support/platform_helpers.rb
+++ b/spec/support/platform_helpers.rb
@@ -51,11 +51,6 @@ def windows_domain_joined?
computer_system["partofdomain"]
end
-def windows_win2k3?
- return false unless windows?
- (host_version && host_version.start_with?("5.2"))
-end
-
def windows_2008r2_or_later?
return false unless windows?
return false unless host_version
@@ -164,6 +159,26 @@ def freebsd?
!!(RUBY_PLATFORM =~ /freebsd/)
end
+def intel_64bit?
+ !!(ohai[:kernel][:machine] == "x86_64")
+end
+
+def rhel?
+ !!(ohai[:platform_family] == "rhel")
+end
+
+def rhel5?
+ rhel? && !!(ohai[:platform_version].to_i == 5)
+end
+
+def rhel6?
+ rhel? && !!(ohai[:platform_version].to_i == 6)
+end
+
+def rhel7?
+ rhel? && !!(ohai[:platform_version].to_i == 7)
+end
+
def debian_family?
!!(ohai[:platform_family] == "debian")
end
@@ -187,7 +202,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
@@ -231,6 +246,9 @@ end
class HttpHelper
extend Ohai::Mixin::HttpHelper
+ def self.logger
+ Chef::Log
+ end
end
def gce?
diff --git a/spec/support/shared/context/client.rb b/spec/support/shared/context/client.rb
index 19ce82fa15..0054058d0f 100644
--- a/spec/support/shared/context/client.rb
+++ b/spec/support/shared/context/client.rb
@@ -11,16 +11,16 @@ shared_context "client" do
let(:ohai_data) do
{
- :fqdn => fqdn,
- :hostname => hostname,
- :machinename => machinename,
- :platform => platform,
- :platform_version => platform_version,
+ fqdn: fqdn,
+ hostname: hostname,
+ machinename: machinename,
+ platform: platform,
+ platform_version: platform_version,
}
end
let(:ohai_system) do
- ohai = instance_double("Ohai::System", :all_plugins => true, :data => ohai_data)
+ ohai = instance_double("Ohai::System", all_plugins: true, data: ohai_data, logger: logger)
allow(ohai).to receive(:[]) do |k|
ohai_data[k]
end
@@ -37,19 +37,24 @@ shared_context "client" do
let(:json_attribs) { nil }
let(:client_opts) { {} }
+ let(:stdout) { STDOUT }
+ let(:stderr) { STDERR }
+
let(:client) do
Chef::Config[:event_loggers] = []
- Chef::Client.new(json_attribs, client_opts).tap do |c|
+ allow(Ohai::System).to receive(:new).and_return(ohai_system)
+ opts = client_opts.merge({ logger: logger })
+ Chef::Client.new(json_attribs, opts).tap do |c|
c.node = node
end
end
- before do
- Chef::Log.logger = Logger.new(StringIO.new)
+ let(:logger) { instance_double("Mixlib::Log::Child", trace: nil, debug: nil, warn: nil, info: nil, error: nil, fatal: nil) }
- # Node/Ohai data
- #Chef::Config[:node_name] = fqdn
- allow(Ohai::System).to receive(:new).and_return(ohai_system)
+ before do
+ stub_const("Chef::Client::STDOUT_FD", stdout)
+ stub_const("Chef::Client::STDERR_FD", stderr)
+ allow(client).to receive(:logger).and_return(logger)
end
end
@@ -75,17 +80,17 @@ shared_context "a client run" do
let(:reporting_rest_client) { double("Chef::ServerAPI (reporting client)") }
let(:runner) { instance_double("Chef::Runner") }
- let(:audit_runner) { instance_double("Chef::Audit::Runner", :failed? => false) }
+ let(:audit_runner) { instance_double("Chef::Audit::Runner", failed?: false) }
def stub_for_register
# --Client.register
# Make sure Client#register thinks the client key doesn't
# exist, so it tries to register and create one.
allow(File).to receive(:exists?).and_call_original
- expect(File).to receive(:exists?).
- with(Chef::Config[:client_key]).
- exactly(:once).
- and_return(api_client_exists?)
+ expect(File).to receive(:exists?)
+ .with(Chef::Config[:client_key])
+ .exactly(:once)
+ .and_return(api_client_exists?)
unless api_client_exists?
# Client.register will register with the validation client name.
@@ -94,21 +99,21 @@ shared_context "a client run" do
end
def stub_for_data_collector_init
- expect(Chef::ServerAPI).to receive(:new).
- with(Chef::Config[:data_collector][:server_url], validate_utf8: false).
- exactly(:once).
- and_return(http_data_collector)
+ expect(Chef::ServerAPI).to receive(:new)
+ .with(Chef::Config[:data_collector][:server_url], validate_utf8: false)
+ .exactly(:once)
+ .and_return(http_data_collector)
end
def stub_for_node_load
# Client.register will then turn around create another
# Chef::ServerAPI object, this time with the client key it got from the
# previous step.
- expect(Chef::ServerAPI).to receive(:new).
- with(Chef::Config[:chef_server_url], client_name: fqdn,
- signing_key_filename: Chef::Config[:client_key]).
- exactly(:once).
- and_return(http_node_load)
+ expect(Chef::ServerAPI).to receive(:new)
+ .with(Chef::Config[:chef_server_url], client_name: fqdn,
+ signing_key_filename: Chef::Config[:client_key])
+ .exactly(:once)
+ .and_return(http_node_load)
# --Client#build_node
# looks up the node, which we will return, then later saves it.
@@ -130,9 +135,9 @@ 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], version_class: Chef::CookbookManifestVersions).and_return(http_cookbook_sync)
- expect(http_cookbook_sync).to receive(:post).
- with("environments/_default/cookbook_versions", { :run_list => [] }).
- and_return({})
+ expect(http_cookbook_sync).to receive(:post)
+ .with("environments/_default/cookbook_versions", { run_list: [] })
+ .and_return({})
end
def stub_for_required_recipe
@@ -162,9 +167,7 @@ shared_context "a client run" do
Chef::Config[:cache_path] = windows? ? 'C:\chef' : "/var/chef"
Chef::Config[:why_run] = false
Chef::Config[:audit_mode] = :enabled
-
- stub_const("Chef::Client::STDOUT_FD", stdout)
- stub_const("Chef::Client::STDERR_FD", stderr)
+ Chef::Config[:chef_guid] = "default-guid"
stub_rest_clean
stub_for_register
@@ -247,8 +250,8 @@ end
shared_context "audit phase completed with failed controls" do
let(:audit_runner) do
- instance_double("Chef::Audit::Runner", :failed? => true,
- :num_failed => 1, :num_total => 3) end
+ instance_double("Chef::Audit::Runner", failed?: true,
+ num_failed: 1, num_total: 3) end
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 3c13cd767e..6479c9d582 100644
--- a/spec/support/shared/examples/client.rb
+++ b/spec/support/shared/examples/client.rb
@@ -14,6 +14,57 @@ shared_examples "a completed run" do
expect(node.automatic_attrs[:platform]).to eq(platform)
expect(node.automatic_attrs[:platform_version]).to eq(platform_version)
end
+
+ describe "setting node GUID" do
+ let(:chef_guid_path) { "/tmp/chef_guid" }
+ let(:chef_guid) { "test-test-test" }
+ let(:metadata_file) { "data_collector_metadata.json" }
+ let(:metadata_path) { Pathname.new(File.join(Chef::Config[:file_cache_path], metadata_file)).cleanpath.to_s }
+ let(:file) { instance_double(File) }
+
+ before do
+ allow(File).to receive(:read).and_call_original
+ Chef::Config[:chef_guid_path] = chef_guid_path
+ Chef::Config[:chef_guid] = nil
+ end
+
+ it "loads from the config" do
+ expect(File).to receive(:exists?).with(chef_guid_path).and_return(true)
+ expect(File).to receive(:read).with(chef_guid_path).and_return(chef_guid)
+ client.run
+ expect(Chef::Config[:chef_guid]).to eql(chef_guid)
+ expect(node.automatic_attrs[:chef_guid]).to eql(chef_guid)
+ end
+
+ it "loads from the data collector config" do
+ expect(File).to receive(:exists?).with(chef_guid_path).and_return(false)
+ expect(Chef::FileCache).to receive(:load).with(metadata_file).and_return("{\"node_uuid\": \"#{chef_guid}\"}")
+
+ expect(File).to receive(:open).with(chef_guid_path, "w+").and_yield(file)
+ expect(file).to receive(:write).with(chef_guid)
+
+ client.run
+ expect(Chef::Config[:chef_guid]).to eql(chef_guid)
+ expect(node.automatic_attrs[:chef_guid]).to eql(chef_guid)
+ end
+
+ it "creates a new one" do
+ expect(File).to receive(:exists?).with(chef_guid_path).and_return(false)
+ expect(File).to receive(:exists?).with(metadata_path).and_return(false)
+
+ expect(SecureRandom).to receive(:uuid).and_return(chef_guid).at_least(:once)
+
+ # we'll try and write the generated UUID to the data collector too, and that's ok
+ allow(File).to receive(:open).with(metadata_path, "w", 420)
+
+ expect(File).to receive(:open).with(chef_guid_path, "w+").and_yield(file)
+ expect(file).to receive(:write).with(chef_guid)
+
+ client.run
+ expect(Chef::Config[:chef_guid]).to eql(chef_guid)
+ expect(node.automatic_attrs[:chef_guid]).to eql(chef_guid)
+ end
+ end
end
shared_examples "a completed run with audit failure" do
diff --git a/spec/support/shared/functional/execute_resource.rb b/spec/support/shared/functional/execute_resource.rb
index 4f7cea1cd1..1a14bb38c3 100644
--- a/spec/support/shared/functional/execute_resource.rb
+++ b/spec/support/shared/functional/execute_resource.rb
@@ -63,7 +63,7 @@ shared_context "a command that can be executed as an alternate user" do
after do
File.delete(script_output_path) if File.exists?(script_output_path)
- Dir.rmdir(script_output_dir) if Dir.exists?(script_output_dir)
+ Dir.rmdir(script_output_dir) if Dir.exist?(script_output_dir)
end
end
diff --git a/spec/support/shared/functional/file_resource.rb b/spec/support/shared/functional/file_resource.rb
index eb7a378db9..d025a0806d 100644
--- a/spec/support/shared/functional/file_resource.rb
+++ b/spec/support/shared/functional/file_resource.rb
@@ -399,7 +399,7 @@ shared_examples_for "a configured file resource" do
content
end
- context "when the target file is a symlink", :not_supported_on_win2k3 do
+ context "when the target file is a symlink" do
let(:symlink_target) do
File.join(CHEF_SPEC_DATA, "file-test-target")
end
diff --git a/spec/support/shared/functional/securable_resource.rb b/spec/support/shared/functional/securable_resource.rb
index 95f4f4bd49..2abae030c2 100644
--- a/spec/support/shared/functional/securable_resource.rb
+++ b/spec/support/shared/functional/securable_resource.rb
@@ -81,7 +81,7 @@ shared_context "use Windows permissions", :windows_only do
SID ||= Chef::ReservedNames::Win32::Security::SID
ACE ||= Chef::ReservedNames::Win32::Security::ACE
ACL ||= Chef::ReservedNames::Win32::Security::ACL
- SecurableObject ||= Chef::ReservedNames::Win32::Security::SecurableObject # rubocop:disable Style/ConstantName
+ SecurableObject ||= Chef::ReservedNames::Win32::Security::SecurableObject # rubocop:disable Naming/ConstantName
end
def get_security_descriptor(path)
@@ -95,7 +95,7 @@ shared_context "use Windows permissions", :windows_only do
def extract_ace_properties(aces)
hashes = []
aces.each do |ace|
- hashes << { :mask => ace.mask, :type => ace.type, :flags => ace.flags }
+ hashes << { mask: ace.mask, type: ace.type, flags: ace.flags }
end
hashes
end
@@ -103,36 +103,36 @@ shared_context "use Windows permissions", :windows_only do
# Standard expected rights
let(:expected_read_perms) do
{
- :generic => Chef::ReservedNames::Win32::API::Security::GENERIC_READ,
- :specific => Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ,
+ generic: Chef::ReservedNames::Win32::API::Security::GENERIC_READ,
+ specific: Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ,
}
end
let(:expected_read_execute_perms) do
{
- :generic => Chef::ReservedNames::Win32::API::Security::GENERIC_READ | Chef::ReservedNames::Win32::API::Security::GENERIC_EXECUTE,
- :specific => Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_EXECUTE,
+ generic: Chef::ReservedNames::Win32::API::Security::GENERIC_READ | Chef::ReservedNames::Win32::API::Security::GENERIC_EXECUTE,
+ specific: Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_EXECUTE,
}
end
let(:expected_write_perms) do
{
- :generic => Chef::ReservedNames::Win32::API::Security::GENERIC_WRITE,
- :specific => Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE,
+ generic: Chef::ReservedNames::Win32::API::Security::GENERIC_WRITE,
+ specific: Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE,
}
end
let(:expected_modify_perms) do
{
- :generic => Chef::ReservedNames::Win32::API::Security::GENERIC_READ | Chef::ReservedNames::Win32::API::Security::GENERIC_WRITE | Chef::ReservedNames::Win32::API::Security::GENERIC_EXECUTE | Chef::ReservedNames::Win32::API::Security::DELETE,
- :specific => Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_EXECUTE | Chef::ReservedNames::Win32::API::Security::DELETE,
+ generic: Chef::ReservedNames::Win32::API::Security::GENERIC_READ | Chef::ReservedNames::Win32::API::Security::GENERIC_WRITE | Chef::ReservedNames::Win32::API::Security::GENERIC_EXECUTE | Chef::ReservedNames::Win32::API::Security::DELETE,
+ specific: Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_READ | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_WRITE | Chef::ReservedNames::Win32::API::Security::FILE_GENERIC_EXECUTE | Chef::ReservedNames::Win32::API::Security::DELETE,
}
end
let(:expected_full_control_perms) do
{
- :generic => Chef::ReservedNames::Win32::API::Security::GENERIC_ALL,
- :specific => Chef::ReservedNames::Win32::API::Security::FILE_ALL_ACCESS,
+ generic: Chef::ReservedNames::Win32::API::Security::GENERIC_ALL,
+ specific: Chef::ReservedNames::Win32::API::Security::FILE_ALL_ACCESS,
}
end
@@ -313,7 +313,7 @@ shared_examples_for "a securable resource without existing target" do
end
it "sets owner when owner is specified with a \\" do
- resource.owner "#{ENV['USERDOMAIN']}\\Guest"
+ resource.owner "#{ENV['COMPUTERNAME']}\\Guest"
resource.run_action(:create)
expect(descriptor.owner).to eq(SID.Guest)
end
@@ -439,12 +439,12 @@ shared_examples_for "a securable resource without existing target" do
context "with a mode attribute" do
if windows?
- Security ||= Chef::ReservedNames::Win32::API::Security # rubocop:disable Style/ConstantName
+ Security ||= Chef::ReservedNames::Win32::API::Security # rubocop:disable Naming/ConstantName
end
it "respects mode in string form as an octal number" do
- #on windows, mode cannot modify owner and/or group permissons
- #unless the owner and/or group as appropriate is specified
+ # on windows, mode cannot modify owner and/or group permissons
+ # unless the owner and/or group as appropriate is specified
resource.mode "400"
resource.owner "Guest"
resource.group "Everyone"
diff --git a/spec/support/shared/functional/securable_resource_with_reporting.rb b/spec/support/shared/functional/securable_resource_with_reporting.rb
index 0bec29783a..abeb1ba4bb 100644
--- a/spec/support/shared/functional/securable_resource_with_reporting.rb
+++ b/spec/support/shared/functional/securable_resource_with_reporting.rb
@@ -19,7 +19,7 @@ ALL_EXPANDED_PERMISSIONS = ["generic read",
"execute / traverse",
"delete child",
"read attributes",
- "write attributes"]
+ "write attributes"].freeze
shared_examples_for "a securable resource with reporting" do
@@ -36,7 +36,7 @@ shared_examples_for "a securable resource with reporting" do
# umask
# let(:default_mode) { (0666 & ~File.umask).to_s(8) }
- describe "reading file security metadata for reporting on unix", :unix_only => true do
+ describe "reading file security metadata for reporting on unix", unix_only: true do
# According to POSIX standard created files get either the
# effective gid of the process or inherits the gid of the parent
# directory based on file system. Since it's hard to guess what
@@ -70,7 +70,7 @@ shared_examples_for "a securable resource with reporting" do
end
end
- context "and owner is specified with a String (username) in new_resource", :requires_root => true do
+ context "and owner is specified with a String (username) in new_resource", requires_root: true do
# TODO/bug: duplicated from the "securable resource" tests
@@ -91,7 +91,7 @@ shared_examples_for "a securable resource with reporting" do
end
- context "and owner is specified with an Integer (uid) in new_resource", :requires_root => true do
+ 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"
@@ -113,7 +113,7 @@ shared_examples_for "a securable resource with reporting" do
end
end
- context "and group is specified with a String (group name)", :requires_root => true do
+ context "and group is specified with a String (group name)", requires_root: true do
let(:expected_group_name) { Etc.getgrent.name }
@@ -128,7 +128,7 @@ shared_examples_for "a securable resource with reporting" do
end
- context "and group is specified with an Integer (gid)", :requires_root => true do
+ context "and group is specified with an Integer (gid)", requires_root: true do
let(:expected_gid) { Etc.getgrent.gid }
before do
diff --git a/spec/support/shared/functional/win32_service.rb b/spec/support/shared/functional/win32_service.rb
index 3199caa34f..a528db4a53 100644
--- a/spec/support/shared/functional/win32_service.rb
+++ b/spec/support/shared/functional/win32_service.rb
@@ -39,11 +39,11 @@ shared_context "using Win32::Service" do
let(:test_service) do
{
- :service_name => "spec-service",
- :service_display_name => "Spec Test Service",
- :service_description => "Service for testing Chef::Application::WindowsServiceManager.",
- :service_file_path => File.expand_path(File.join(File.dirname(__FILE__), "../../platforms/win32/spec_service.rb")),
- :delayed_start => true,
+ service_name: "spec-service",
+ service_display_name: "Spec Test Service",
+ service_description: "Service for testing Chef::Application::WindowsServiceManager.",
+ service_file_path: File.expand_path(File.join(File.dirname(__FILE__), "../../platforms/win32/spec_service.rb")),
+ delayed_start: true,
}
end
diff --git a/spec/support/shared/functional/windows_script.rb b/spec/support/shared/functional/windows_script.rb
index e5ac0741bd..5eb68952d7 100644
--- a/spec/support/shared/functional/windows_script.rb
+++ b/spec/support/shared/functional/windows_script.rb
@@ -93,7 +93,7 @@ shared_context Chef::Resource::WindowsScript do
context "when the guard's architecture is specified as 64-bit" do
let (:guard_architecture) { :x86_64 }
it "executes a 64-bit guard", :windows64_only do
- resource.only_if resource_guard_command, :architecture => guard_architecture
+ resource.only_if resource_guard_command, architecture: guard_architecture
resource.run_action(:run)
expect(get_guard_process_architecture).to eq("amd64")
end
@@ -102,7 +102,7 @@ shared_context Chef::Resource::WindowsScript do
context "when the guard's architecture is specified as 32-bit", :not_supported_on_nano do
let (:guard_architecture) { :i386 }
it "executes a 32-bit guard" do
- resource.only_if resource_guard_command, :architecture => guard_architecture
+ resource.only_if resource_guard_command, architecture: guard_architecture
resource.run_action(:run)
expect(get_guard_process_architecture).to eq("x86")
end
@@ -111,7 +111,7 @@ shared_context Chef::Resource::WindowsScript do
context "when the guard's architecture is specified as 32-bit", :windows_nano_only do
let (:guard_architecture) { :i386 }
it "raises an error" do
- resource.only_if resource_guard_command, :architecture => guard_architecture
+ resource.only_if resource_guard_command, architecture: guard_architecture
expect { resource.run_action(:run) }.to raise_error(
Chef::Exceptions::Win32ArchitectureIncorrect,
/cannot execute script with requested architecture 'i386' on Windows Nano Server/)
diff --git a/spec/support/shared/integration/app_server_support.rb b/spec/support/shared/integration/app_server_support.rb
index e2bb3812ea..c0b24d9443 100644
--- a/spec/support/shared/integration/app_server_support.rb
+++ b/spec/support/shared/integration/app_server_support.rb
@@ -25,9 +25,9 @@ module AppServerSupport
server = nil
thread = Thread.new do
Rack::Handler::WEBrick.run(app,
- :Port => 9018,
- :AccessLog => [],
- :Logger => WEBrick::Log.new(StringIO.new, 7)
+ Port: 9018,
+ AccessLog: [],
+ Logger: WEBrick::Log.new(StringIO.new, 7)
) do |found_server|
server = found_server
end
diff --git a/spec/support/shared/integration/integration_helper.rb b/spec/support/shared/integration/integration_helper.rb
index 29f2eef50f..5fc9de4de7 100644
--- a/spec/support/shared/integration/integration_helper.rb
+++ b/spec/support/shared/integration/integration_helper.rb
@@ -140,12 +140,12 @@ module IntegrationSupport
# Versioned cookbooks
- RSpec.shared_context "with versioned cookbooks", :versioned_cookbooks => true do
+ RSpec.shared_context "with versioned cookbooks", versioned_cookbooks: true do
before(:each) { Chef::Config[:versioned_cookbooks] = true }
after(:each) { Chef::Config.delete(:versioned_cookbooks) }
end
- RSpec.shared_context "without versioned cookbooks", :versioned_cookbooks => false do
+ RSpec.shared_context "without versioned cookbooks", versioned_cookbooks: false do
# Just make sure this goes back to default
before(:each) { Chef::Config[:versioned_cookbooks] = false }
after(:each) { Chef::Config.delete(:versioned_cookbooks) }
diff --git a/spec/support/shared/integration/knife_support.rb b/spec/support/shared/integration/knife_support.rb
index d873723784..87ce1bc0b0 100644
--- a/spec/support/shared/integration/knife_support.rb
+++ b/spec/support/shared/integration/knife_support.rb
@@ -24,7 +24,7 @@ require "chef/chef_fs/file_system_cache"
module KnifeSupport
DEBUG = ENV["DEBUG"]
- def knife(*args, input: nil)
+ def knife(*args, input: nil, instance_filter: nil)
# Allow knife('role from file roles/blah.json') rather than requiring the
# arguments to be split like knife('role', 'from', 'file', 'roles/blah.json')
# If any argument will have actual spaces in it, the long form is required.
@@ -40,8 +40,8 @@ module KnifeSupport
# Work on machines where we can't access /var
Dir.mktmpdir("checksums") do |checksums_cache_dir|
Chef::Config[:cache_options] = {
- :path => checksums_cache_dir,
- :skip_expires => true,
+ path: checksums_cache_dir,
+ skip_expires: true,
}
# This is Chef::Knife.run without load_commands--we'll load stuff
@@ -83,9 +83,20 @@ module KnifeSupport
# running test scenarios against a real chef server. If things don't
# smell right, abort.
+ # To ensure that we don't pick up a user's credentials file we lie through our teeth about
+ # it's existence.
+ allow(File).to receive(:file?).and_call_original
+ allow(File).to receive(:file?).with(File.expand_path("~/.chef/credentials")).and_return(false)
+
+ # Set a canary that is modified by the default null_config.rb config file.
$__KNIFE_INTEGRATION_FAILSAFE_CHECK = "ole"
+
+ # Allow tweaking the knife instance before configuration.
+ instance_filter.call(instance) if instance_filter
+
instance.configure_chef
+ # The canary is incorrect, meaning the normal null_config.rb didn't run. Something is wrong.
unless $__KNIFE_INTEGRATION_FAILSAFE_CHECK == "ole ole"
raise Exception, "Potential misconfiguration of integration tests detected. Aborting test."
end
diff --git a/spec/support/shared/unit/api_error_inspector.rb b/spec/support/shared/unit/api_error_inspector.rb
index 45bfcc67da..15c122e3dc 100644
--- a/spec/support/shared/unit/api_error_inspector.rb
+++ b/spec/support/shared/unit/api_error_inspector.rb
@@ -28,15 +28,15 @@ shared_examples_for "an api error inspector" do
before do
@node_name = "test-node.example.com"
@config = {
- :validation_client_name => "testorg-validator",
- :validation_key => "/etc/chef/testorg-validator.pem",
- :chef_server_url => "https://chef-api.example.com",
- :node_name => "testnode-name",
- :client_key => "/etc/chef/client.pem",
+ validation_client_name: "testorg-validator",
+ validation_key: "/etc/chef/testorg-validator.pem",
+ chef_server_url: "https://chef-api.example.com",
+ node_name: "testnode-name",
+ client_key: "/etc/chef/client.pem",
}
@description = Chef::Formatters::ErrorDescription.new("Error registering the node:")
@outputter = Chef::Formatters::IndentableOutputStream.new(StringIO.new, STDERR)
- #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
+ # @outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
end
diff --git a/spec/support/shared/unit/api_versioning.rb b/spec/support/shared/unit/api_versioning.rb
index 28141b73b1..9c179efa82 100644
--- a/spec/support/shared/unit/api_versioning.rb
+++ b/spec/support/shared/unit/api_versioning.rb
@@ -19,7 +19,7 @@
require "chef/exceptions"
shared_examples_for "version handling" do
- let(:response_406) { OpenStruct.new(:code => "406") }
+ let(:response_406) { OpenStruct.new(code: "406") }
let(:exception_406) { Net::HTTPServerException.new("406 Not Acceptable", response_406) }
before do
@@ -38,7 +38,7 @@ shared_examples_for "version handling" do
end # version handling
shared_examples_for "user and client reregister" do
- let(:response_406) { OpenStruct.new(:code => "406") }
+ let(:response_406) { OpenStruct.new(code: "406") }
let(:exception_406) { Net::HTTPServerException.new("406 Not Acceptable", response_406) }
let(:generic_exception) { Exception.new }
let(:min_version) { "2" }
diff --git a/spec/support/shared/unit/application_dot_d.rb b/spec/support/shared/unit/application_dot_d.rb
index da4eb88edd..b94fa7c184 100644
--- a/spec/support/shared/unit/application_dot_d.rb
+++ b/spec/support/shared/unit/application_dot_d.rb
@@ -38,9 +38,11 @@ shared_examples_for "an application that loads a dot d" do
it "loads the configuration in order" do
expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/00-foo.rb").cleanpath.to_s).and_return("foo 0")
expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/01-bar.rb").cleanpath.to_s).and_return("bar 0")
+ expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/02-strings.rb").cleanpath.to_s).and_return("strings 0")
allow(app).to receive(:apply_config).with(anything(), Chef::Config.platform_specific_path("/etc/chef/client.rb")).and_call_original.ordered
expect(app).to receive(:apply_config).with("foo 0", Pathname.new("#{client_d_dir}/00-foo.rb").cleanpath.to_s).and_call_original.ordered
expect(app).to receive(:apply_config).with("bar 0", Pathname.new("#{client_d_dir}/01-bar.rb").cleanpath.to_s).and_call_original.ordered
+ expect(app).to receive(:apply_config).with("strings 0", Pathname.new("#{client_d_dir}/02-strings.rb").cleanpath.to_s).and_call_original.ordered
app.reconfigure
end
end
diff --git a/spec/support/shared/unit/execute_resource.rb b/spec/support/shared/unit/execute_resource.rb
index ae56a9697d..05c2fc4a9a 100644
--- a/spec/support/shared/unit/execute_resource.rb
+++ b/spec/support/shared/unit/execute_resource.rb
@@ -22,7 +22,7 @@ require "spec_helper"
shared_examples_for "an execute resource" do
before(:each) do
- @resource = execute_resource
+ @resource = resource
end
it "should create a new Chef::Resource::Execute" do
@@ -57,7 +57,7 @@ shared_examples_for "an execute resource" do
end
it "should accept a hash for the environment" do
- test_hash = { :one => :two }
+ test_hash = { one: :two }
@resource.environment(test_hash)
expect(@resource.environment).to eql(test_hash)
end
@@ -139,7 +139,14 @@ shared_examples_for "an execute resource" do
it "should be true if the password is non-nil but the value is explicitly set to false" do
@resource.password("we.funk!")
@resource.sensitive false
- expect(@resource.sensitive).to eq(true)
+ expect(@resource.sensitive).to eq(false)
+ end
+
+ # added this test to ensure setting of password property after or before sensitive does not matter
+ it "should be false if the sensitive is set before password property" do
+ @resource.sensitive false
+ @resource.password("we.funk!")
+ expect(@resource.sensitive).to eq(false)
end
end
@@ -148,7 +155,7 @@ shared_examples_for "an execute resource" do
before do
@resource.command("grep")
@resource.cwd("/tmp/")
- @resource.environment({ :one => :two })
+ @resource.environment({ one: :two })
@resource.group("legos")
@resource.returns(1)
@resource.user("root")
diff --git a/spec/support/shared/unit/provider/file.rb b/spec/support/shared/unit/provider/file.rb
index b58159fcc9..a7c7af92f6 100644
--- a/spec/support/shared/unit/provider/file.rb
+++ b/spec/support/shared/unit/provider/file.rb
@@ -258,11 +258,11 @@ shared_examples_for Chef::Provider::File do
allow(ChefConfig).to receive(:windows?).and_return(false)
# mock up the filesystem to behave like unix
setup_normal_file
- stat_struct = double("::File.stat", :mode => 0600, :uid => 0, :gid => 0, :mtime => 10000)
+ stat_struct = double("::File.stat", mode: 0600, uid: 0, gid: 0, mtime: 10000)
resource_real_path = File.realpath(resource.path)
expect(File).to receive(:stat).with(resource_real_path).at_least(:once).and_return(stat_struct)
- allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel"))
- allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", :name => "root"))
+ allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", name: "wheel"))
+ allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", name: "root"))
end
context "when the new_resource does not specify any state" do
@@ -383,11 +383,11 @@ shared_examples_for Chef::Provider::File do
allow(ChefConfig).to receive(:windows?).and_return(false)
# mock up the filesystem to behave like unix
setup_normal_file
- stat_struct = double("::File.stat", :mode => 0600, :uid => 0, :gid => 0, :mtime => 10000)
+ stat_struct = double("::File.stat", mode: 0600, uid: 0, gid: 0, mtime: 10000)
resource_real_path = File.realpath(resource.path)
allow(File).to receive(:stat).with(resource_real_path).and_return(stat_struct)
- allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", :name => "wheel"))
- allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", :name => "root"))
+ allow(Etc).to receive(:getgrgid).with(0).and_return(double("Group Ent", name: "wheel"))
+ allow(Etc).to receive(:getpwuid).with(0).and_return(double("User Ent", name: "root"))
provider.send(:load_resource_attributes_from_file, resource)
end
@@ -460,7 +460,7 @@ shared_examples_for Chef::Provider::File do
before { setup_normal_file }
let(:tempfile) do
- t = double("Tempfile", :path => "/tmp/foo-bar-baz", :closed? => true)
+ t = double("Tempfile", path: "/tmp/foo-bar-baz", closed?: true)
allow(content).to receive(:tempfile).and_return(t)
t
end
@@ -476,7 +476,15 @@ 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, "Proposed content for #{provider.new_resource.path} failed verification #{windows? ? "cmd.exe /c exit 1" : "false"}")
+ end
+
+ it "does not show verification for sensitive resources" 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"
+ provider.new_resource.sensitive true
+ expect { provider.send(:do_validate_content) }.to raise_error(Chef::Exceptions::ValidationFailed, "Proposed content for #{provider.new_resource.path} failed verification [sensitive]")
end
end
end
@@ -507,7 +515,7 @@ shared_examples_for Chef::Provider::File do
before do
setup_normal_file
provider.load_current_resource
- tempfile = double("Tempfile", :path => "/tmp/foo-bar-baz")
+ tempfile = double("Tempfile", path: "/tmp/foo-bar-baz")
allow(content).to receive(:tempfile).and_return(tempfile)
expect(File).to receive(:exists?).with("/tmp/foo-bar-baz").and_return(true)
expect(tempfile).to receive(:close).once
@@ -520,8 +528,8 @@ 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"],
- :for_reporting => diff_for_reporting )
+ 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)
@@ -584,13 +592,13 @@ shared_examples_for Chef::Provider::File do
end
it "raises an exception when the content object returns a tempfile with a nil path" do
- tempfile = double("Tempfile", :path => nil)
+ 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(RuntimeError)
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")
+ 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(RuntimeError)
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 cc2d22f64f..a30f543e72 100644
--- a/spec/support/shared/unit/provider/useradd_based_user_provider.rb
+++ b/spec/support/shared/unit/provider/useradd_based_user_provider.rb
@@ -1,7 +1,7 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
#
# License:: Apache License, Version 2.0
#
@@ -68,8 +68,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
@@ -160,7 +160,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
"-d", "/Users/mud",
"-m",
"adam" ])
- expect(provider).to receive(:shell_out!).with(*command).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with(*command).and_return(true)
provider.create_user
end
@@ -181,7 +181,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
"-u", "1000",
"-r", "-m",
"adam" ])
- expect(provider).to receive(:shell_out!).with(*command).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with(*command).and_return(true)
provider.create_user
end
@@ -204,7 +204,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
"-d", "/Users/mud",
"-m",
"adam" ]
- expect(provider).to receive(:shell_out!).with(*command).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with(*command).and_return(true)
provider.manage_user
end
@@ -215,7 +215,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
"-d", "/Users/mud",
"-m",
"adam" ]
- expect(provider).to receive(:shell_out!).with(*command).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with(*command).and_return(true)
provider.manage_user
end
@@ -224,7 +224,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
command = ["usermod",
"-g", "23",
"adam" ]
- expect(provider).to receive(:shell_out!).with(*command).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with(*command).and_return(true)
provider.manage_user
end
end
@@ -232,24 +232,24 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
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)
+ expect(provider).to receive(:shell_out_compacted!).with("userdel", @new_resource.username).and_return(true)
provider.remove_user
end
it "should run userdel with the new resources user name and -r if manage_home is true" do
@new_resource.manage_home true
- expect(provider).to receive(:shell_out!).with("userdel", "-r", @new_resource.username).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).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
- expect(provider).to receive(:shell_out!).with("userdel", @new_resource.username).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with("userdel", @new_resource.username).and_return(true)
provider.remove_user
end
it "should run userdel with the new resources user name and -f if force is true" do
@new_resource.force(true)
- expect(provider).to receive(:shell_out!).with("userdel", "-f", @new_resource.username).and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with("userdel", "-f", @new_resource.username).and_return(true)
provider.remove_user
end
end
@@ -257,7 +257,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
describe "when checking the lock" do
# lazy initialize so we can modify stdout and stderr strings
let(:passwd_s_status) do
- double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => @stdout, :stderr => @stderr, :error! => nil)
+ double("Mixlib::ShellOut command", exitstatus: 0, stdout: @stdout, stderr: @stderr, error!: nil)
end
before(:each) do
@@ -266,57 +266,57 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
# :nil_object => true,
# :username => "adam"
# )
- #provider = Chef::Provider::User::Useradd.new(@node, @new_resource)
+ # provider = Chef::Provider::User::Useradd.new(@node, @new_resource)
@stdout = "root P 09/02/2008 0 99999 7 -1"
@stderr = ""
end
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] }).
- and_return(passwd_s_status)
+ expect(provider).to receive(:shell_out)
+ .with("passwd", "-S", @new_resource.username, { returns: [0, 1] })
+ .and_return(passwd_s_status)
expect(provider.check_lock).to eql(false)
end
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] }).
- and_return(passwd_s_status)
+ expect(provider).to receive(:shell_out)
+ .with("passwd", "-S", @new_resource.username, { returns: [0, 1] })
+ .and_return(passwd_s_status)
expect(provider.check_lock).to eql(false)
end
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] }).
- and_return(passwd_s_status)
+ expect(provider).to receive(:shell_out)
+ .with("passwd", "-S", @new_resource.username, { returns: [0, 1] })
+ .and_return(passwd_s_status)
expect(provider.check_lock).to eql(true)
end
it "should raise a ShellCommandFailed exception if passwd -S exits with something other than 0 or 1" do
expect(passwd_s_status).to receive(:error!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
- expect(provider).to receive(:shell_out).
- with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }).
- and_return(passwd_s_status)
+ expect(provider).to receive(:shell_out)
+ .with("passwd", "-S", @new_resource.username, { returns: [0, 1] })
+ .and_return(passwd_s_status)
expect { provider.check_lock }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
it "should raise an error if the output isn't parsable" do
expect(passwd_s_status).to receive(:stdout).and_return("")
expect(passwd_s_status).to receive(:stderr).and_return("")
- expect(provider).to receive(:shell_out).
- with("passwd", "-S", @new_resource.username, { :returns => [0, 1] }).
- and_return(passwd_s_status)
+ expect(provider).to receive(:shell_out)
+ .with("passwd", "-S", @new_resource.username, { returns: [0, 1] })
+ .and_return(passwd_s_status)
expect { provider.check_lock }.to raise_error(Chef::Exceptions::User)
end
context "when in why run mode" do
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] }).
- and_return(passwd_status)
+ 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] })
+ .and_return(passwd_status)
# ubuntu returns 252 on user-does-not-exist so will raise if #error! is called or if
# shell_out! is used
allow(passwd_status).to receive(:error!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
@@ -335,14 +335,14 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
describe "when locking the user" do
it "should run usermod -L with the new resources username" do
- expect(provider).to receive(:shell_out!).with("usermod", "-L", @new_resource.username)
+ expect(provider).to receive(:shell_out_compacted!).with("usermod", "-L", @new_resource.username)
provider.lock_user
end
end
describe "when unlocking the user" do
it "should run usermod -L with the new resources username" do
- expect(provider).to receive(:shell_out!).with("usermod", "-U", @new_resource.username)
+ expect(provider).to receive(:shell_out_compacted!).with("usermod", "-U", @new_resource.username)
provider.unlock_user
end
end
@@ -385,7 +385,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
expect(Pathname).to receive(:new).with(@new_resource.home).and_return(@new_home_mock)
expect(@new_home_mock).to receive(:cleanpath).and_return(home_check["new_resource_home"].last)
- expect(provider.updating_home?).to eq(home_check["expected_result"])
+ expect(provider.send(:updating_home?)).to eq(home_check["expected_result"])
end
end
it "should return true if the current home does not exist but a home is specified by the new resource" do
@@ -396,7 +396,7 @@ shared_examples_for "a useradd-based user provider" do |supported_useradd_option
@current_resource.home nil
@new_resource.home "/home/kitten"
- expect(provider.updating_home?).to eq(true)
+ expect(provider.send(:updating_home?)).to eq(true)
end
end
end
diff --git a/spec/support/shared/unit/user_and_client_shared.rb b/spec/support/shared/unit/user_and_client_shared.rb
index 6c31ca22d1..40042933e2 100644
--- a/spec/support/shared/unit/user_and_client_shared.rb
+++ b/spec/support/shared/unit/user_and_client_shared.rb
@@ -27,7 +27,7 @@ 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
@@ -49,7 +49,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
@@ -104,7 +104,7 @@ 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
diff --git a/spec/tiny_server.rb b/spec/tiny_server.rb
index 83c5bf4a42..4a6bdfb599 100644
--- a/spec/tiny_server.rb
+++ b/spec/tiny_server.rb
@@ -38,7 +38,7 @@ module TinyServer
# SSLEnable: options[:ssl],
# SSLCertName: [ [ 'CN', WEBrick::Utils::getservername ] ],
AccessLog: [], # Remove this option to enable the access log when debugging.
- }
+ }.freeze
def initialize(**options)
@options = DEFAULT_OPTIONS.merge(options)
@@ -101,10 +101,10 @@ module TinyServer
class API
include Singleton
- GET = "GET"
- PUT = "PUT"
- POST = "POST"
- DELETE = "DELETE"
+ GET = "GET".freeze
+ PUT = "PUT".freeze
+ POST = "POST".freeze
+ DELETE = "DELETE".freeze
attr_reader :routes
@@ -136,8 +136,8 @@ 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) ]]
@@ -170,7 +170,7 @@ module TinyServer
end
class Response
- HEADERS = { "Content-Type" => "application/json" }
+ HEADERS = { "Content-Type" => "application/json" }.freeze
def initialize(response_code = 200, data = nil, headers = nil, &block)
@response_code, @data = response_code, data
diff --git a/spec/unit/api_client/registration_spec.rb b/spec/unit/api_client/registration_spec.rb
index 0f036766da..407c2c9f07 100644
--- a/spec/unit/api_client/registration_spec.rb
+++ b/spec/unit/api_client/registration_spec.rb
@@ -38,11 +38,11 @@ describe Chef::ApiClient::Registration do
let(:http_mock) { double("Chef::ServerAPI mock") }
let(:expected_post_data) do
- { :name => client_name, :admin => false, :public_key => generated_public_key.to_pem }
+ { name: client_name, admin: false, public_key: generated_public_key.to_pem }
end
let(:expected_put_data) do
- { :name => client_name, :admin => false, :public_key => generated_public_key.to_pem }
+ { name: client_name, admin: false, public_key: generated_public_key.to_pem }
end
let(:server_v10_response) do
@@ -108,28 +108,28 @@ describe Chef::ApiClient::Registration do
end
it "posts a locally generated public key to the server to create a client" do
- expect(http_mock).to receive(:post).
- with("clients", expected_post_data).
- and_return(create_with_pkey_response)
+ expect(http_mock).to receive(:post)
+ .with("clients", expected_post_data)
+ .and_return(create_with_pkey_response)
expect(registration.run.public_key).to eq(create_with_pkey_response["chef_key"]["public_key"])
expect(OpenSSL::PKey::RSA.new(registration.private_key).to_s).to eq(OpenSSL::PKey::RSA.new(generated_private_key_pem).to_s)
end
it "puts a locally generated public key to the server to update a client" do
- expect(http_mock).to receive(:post).
- with("clients", expected_post_data).
- and_raise(exception_409)
- expect(http_mock).to receive(:put).
- with("clients/#{client_name}", expected_put_data).
- and_return(update_with_pkey_response)
+ expect(http_mock).to receive(:post)
+ .with("clients", expected_post_data)
+ .and_raise(exception_409)
+ expect(http_mock).to receive(:put)
+ .with("clients/#{client_name}", expected_put_data)
+ .and_return(update_with_pkey_response)
expect(registration.run.public_key).to eq(update_with_pkey_response["public_key"].to_pem)
expect(OpenSSL::PKey::RSA.new(registration.private_key).to_s).to eq(OpenSSL::PKey::RSA.new(generated_private_key_pem).to_s)
end
it "writes the generated private key to disk" do
- expect(http_mock).to receive(:post).
- with("clients", expected_post_data).
- and_return(create_with_pkey_response)
+ expect(http_mock).to receive(:post)
+ .with("clients", expected_post_data)
+ .and_return(create_with_pkey_response)
registration.run
expect(OpenSSL::PKey::RSA.new(IO.read(key_location)).to_s).to eq(OpenSSL::PKey::RSA.new(generated_private_key_pem).to_s)
end
@@ -137,9 +137,9 @@ describe Chef::ApiClient::Registration do
context "and the client already exists on a Chef 11 server" do
it "requests a new key from the server and saves it" do
expect(http_mock).to receive(:post).and_raise(exception_409)
- expect(http_mock).to receive(:put).
- with("clients/#{client_name}", expected_put_data).
- and_return(update_with_pkey_response)
+ expect(http_mock).to receive(:put)
+ .with("clients/#{client_name}", expected_put_data)
+ .and_return(update_with_pkey_response)
expect(registration.run.public_key).to eq(update_with_pkey_response["public_key"].to_pem)
expect(OpenSSL::PKey::RSA.new(registration.private_key).to_s).to eq(OpenSSL::PKey::RSA.new(generated_private_key_pem).to_s)
end
@@ -148,11 +148,11 @@ describe Chef::ApiClient::Registration do
context "when local key generation is disabled" do
let(:expected_post_data) do
- { :name => client_name, :admin => false }
+ { name: client_name, admin: false }
end
let(:expected_put_data) do
- { :name => client_name, :admin => false, :private_key => true }
+ { name: client_name, admin: false, private_key: true }
end
before do
@@ -161,9 +161,9 @@ describe Chef::ApiClient::Registration do
end
it "creates a new ApiClient on the server using the validator identity" do
- expect(http_mock).to receive(:post).
- with("clients", expected_post_data).
- and_return(server_v10_response)
+ expect(http_mock).to receive(:post)
+ .with("clients", expected_post_data)
+ .and_return(server_v10_response)
expect(registration.run.private_key).to eq(server_v10_response["private_key"])
expect(registration.private_key).to eq("--begin rsa key etc--")
end
@@ -171,9 +171,9 @@ describe Chef::ApiClient::Registration do
context "and the client already exists on a Chef 11 server" do
it "requests a new key from the server and saves it" do
expect(http_mock).to receive(:post).and_raise(exception_409)
- expect(http_mock).to receive(:put).
- with("clients/#{client_name}", expected_put_data).
- and_return(server_v11_response)
+ expect(http_mock).to receive(:put)
+ .with("clients/#{client_name}", expected_put_data)
+ .and_return(server_v11_response)
expect(registration.run).to eq(server_v11_response)
expect(registration.private_key).to eq("--begin rsa key etc--")
end
@@ -181,11 +181,11 @@ describe Chef::ApiClient::Registration do
context "and the client already exists on a Chef 10 server" do
it "requests a new key from the server and saves it" do
- expect(http_mock).to receive(:post).with("clients", expected_post_data).
- and_raise(exception_409)
- expect(http_mock).to receive(:put).
- with("clients/#{client_name}", expected_put_data).
- and_return(server_v10_response)
+ expect(http_mock).to receive(:post).with("clients", expected_post_data)
+ .and_raise(exception_409)
+ expect(http_mock).to receive(:put)
+ .with("clients/#{client_name}", expected_put_data)
+ .and_return(server_v10_response)
expect(registration.run.private_key).to eq(server_v10_response["private_key"])
expect(registration.private_key).to eq("--begin rsa key etc--")
end
diff --git a/spec/unit/api_client_spec.rb b/spec/unit/api_client_spec.rb
index a8ac4f747b..e83906e712 100644
--- a/spec/unit/api_client_spec.rb
+++ b/spec/unit/api_client_spec.rb
@@ -302,9 +302,9 @@ describe Chef::ApiClient do
@api_client_with_key = Chef::ApiClient.new
@api_client_with_key.name("lost-my-key")
@api_client_with_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)
+ 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)
end
it "returns an ApiClient with a private key" do
@@ -320,9 +320,9 @@ 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" }
- 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)
+ 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)
end
it "returns an ApiClient with a private key" do
diff --git a/spec/unit/api_client_v1_spec.rb b/spec/unit/api_client_v1_spec.rb
index 9c643fa492..802384534b 100644
--- a/spec/unit/api_client_v1_spec.rb
+++ b/spec/unit/api_client_v1_spec.rb
@@ -324,13 +324,13 @@ describe Chef::ApiClientV1 do
end
describe "Versioned API Interactions" do
- let(:response_406) { OpenStruct.new(:code => "406") }
+ let(:response_406) { OpenStruct.new(code: "406") }
let(:exception_406) { Net::HTTPServerException.new("406 Not Acceptable", response_406) }
let(:payload) do
{
- :name => "some_name",
- :validator => true,
- :admin => true,
+ name: "some_name",
+ validator: true,
+ admin: true,
}
end
@@ -389,7 +389,7 @@ 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
@@ -437,7 +437,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
diff --git a/spec/unit/application/apply_spec.rb b/spec/unit/application/apply_spec.rb
index 0af3916134..b659f13fe8 100644
--- a/spec/unit/application/apply_spec.rb
+++ b/spec/unit/application/apply_spec.rb
@@ -37,7 +37,7 @@ describe Chef::Application::Apply do
before do
@recipe_file_name = "foo.rb"
@recipe_path = File.expand_path(@recipe_file_name)
- @recipe_file = double("Tempfile (mock)", :read => @recipe_text)
+ @recipe_file = double("Tempfile (mock)", read: @recipe_text)
allow(@app).to receive(:open).with(@recipe_path).and_return(@recipe_file)
allow(File).to receive(:exist?).with(@recipe_path).and_return(true)
allow(Chef::Application).to receive(:fatal!).and_return(true)
@@ -96,13 +96,13 @@ describe Chef::Application::Apply do
end
describe "when the json_attribs configuration option is specified" do
let(:json_attribs) { { "a" => "b" } }
- let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) }
+ let(:config_fetcher) { double(Chef::ConfigFetcher, fetch_json: json_attribs) }
let(:json_source) { "https://foo.com/foo.json" }
before do
Chef::Config[:json_attribs] = json_source
- expect(Chef::ConfigFetcher).to receive(:new).with(json_source).
- and_return(config_fetcher)
+ expect(Chef::ConfigFetcher).to receive(:new).with(json_source)
+ .and_return(config_fetcher)
end
it "reads the JSON attributes from the specified source" do
diff --git a/spec/unit/application/client_spec.rb b/spec/unit/application/client_spec.rb
index 825a4e7aac..40f690abb1 100644
--- a/spec/unit/application/client_spec.rb
+++ b/spec/unit/application/client_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: AJ Christensen (<aj@junglist.gen.nz>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -107,6 +107,7 @@ describe Chef::Application::Client, "reconfigure" do
shared_examples "sets the configuration" do |cli_arguments, expected_config|
describe cli_arguments do
before do
+ cli_arguments ||= ""
ARGV.replace(cli_arguments.split)
app.reconfigure
end
@@ -120,44 +121,74 @@ describe Chef::Application::Client, "reconfigure" do
describe "--named-run-list" do
it_behaves_like "sets the configuration",
"--named-run-list arglebargle-example",
- :named_run_list => "arglebargle-example"
+ named_run_list: "arglebargle-example"
end
describe "--no-listen" do
- it_behaves_like "sets the configuration", "--no-listen", :listen => false
+ it_behaves_like "sets the configuration", "--no-listen", listen: false
end
describe "--daemonize", :unix_only do
context "with no value" do
it_behaves_like "sets the configuration", "--daemonize",
- :daemonize => true
+ daemonize: true
end
context "with an integer value" do
it_behaves_like "sets the configuration", "--daemonize 5",
- :daemonize => 5
+ daemonize: 5
end
context "with a non-integer value" do
it_behaves_like "sets the configuration", "--daemonize foo",
- :daemonize => true
+ daemonize: true
+ end
+ end
+
+ describe "--[no]-fork" do
+ before do
+ Chef::Config[:interval] = nil # FIXME: we're overriding the before block setting this
+ end
+
+ context "by default" do
+ it_behaves_like "sets the configuration", "", client_fork: false
+ end
+
+ context "with --fork" do
+ it_behaves_like "sets the configuration", "--fork", client_fork: true
+ end
+
+ context "with --no-fork" do
+ it_behaves_like "sets the configuration", "--no-fork", client_fork: false
+ end
+
+ context "with an interval" do
+ it_behaves_like "sets the configuration", "--interval 1800", client_fork: true
+ end
+
+ context "with once" do
+ it_behaves_like "sets the configuration", "--once", client_fork: false
+ end
+
+ context "with daemonize", :unix_only do
+ it_behaves_like "sets the configuration", "--daemonize", client_fork: true
end
end
describe "--config-option" do
context "with a single value" do
it_behaves_like "sets the configuration", "--config-option chef_server_url=http://example",
- :chef_server_url => "http://example"
+ chef_server_url: "http://example"
end
context "with two values" do
it_behaves_like "sets the configuration", "--config-option chef_server_url=http://example --config-option policy_name=web",
- :chef_server_url => "http://example", :policy_name => "web"
+ chef_server_url: "http://example", policy_name: "web"
end
context "with a boolean value" do
it_behaves_like "sets the configuration", "--config-option minimal_ohai=true",
- :minimal_ohai => true
+ minimal_ohai: true
end
context "with an empty value" do
@@ -186,21 +217,16 @@ describe Chef::Application::Client, "reconfigure" do
Chef::Config[:splay] = nil
end
- context "when interval is given" do
- before do
- Chef::Config[:interval] = 600
- allow(ChefConfig).to receive(:windows?).and_return(false)
- end
-
- it "should terminate with message" do
- expect(Chef::Application).to receive(:fatal!).with(
-"Unforked chef-client interval runs are disabled in Chef 12.
+ it "should terminal with message when interval is given" do
+ Chef::Config[:interval] = 600
+ allow(ChefConfig).to receive(:windows?).and_return(false)
+ expect(Chef::Application).to receive(:fatal!).with(
+ "Unforked chef-client interval runs are disabled in Chef 12.
Configuration settings:
interval = 600 seconds
Enable chef-client interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options."
- )
- app.reconfigure
- end
+ )
+ app.reconfigure
end
context "when interval is given on windows" do
@@ -295,14 +321,14 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config
describe "when the json_attribs configuration option is specified" do
let(:json_attribs) { { "a" => "b" } }
- let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) }
+ let(:config_fetcher) { double(Chef::ConfigFetcher, fetch_json: json_attribs) }
let(:json_source) { "https://foo.com/foo.json" }
before do
allow(app).to receive(:configure_chef).and_return(true)
Chef::Config[:json_attribs] = json_source
- expect(Chef::ConfigFetcher).to receive(:new).with(json_source).
- and_return(config_fetcher)
+ expect(Chef::ConfigFetcher).to receive(:new).with(json_source)
+ .and_return(config_fetcher)
end
it "reads the JSON attributes from the specified source" do
@@ -421,6 +447,7 @@ describe Chef::Application::Client, "configure_chef" do
before do
@original_argv = ARGV.dup
ARGV.clear
+ allow(::File).to receive(:read).and_call_original
allow(::File).to receive(:read).with(Chef::Config.platform_specific_path("/etc/chef/client.rb")).and_return("")
app.configure_chef
end
diff --git a/spec/unit/application/knife_spec.rb b/spec/unit/application/knife_spec.rb
index 90ecde608e..8a574b4d0f 100644
--- a/spec/unit/application/knife_spec.rb
+++ b/spec/unit/application/knife_spec.rb
@@ -24,9 +24,9 @@ describe Chef::Application::Knife do
before(:all) do
class NoopKnifeCommand < Chef::Knife
option :opt_with_default,
- :short => "-D VALUE",
- :long => "-optwithdefault VALUE",
- :default => "default-value"
+ short: "-D VALUE",
+ long: "-optwithdefault VALUE",
+ default: "default-value"
def run
end
diff --git a/spec/unit/application/solo_spec.rb b/spec/unit/application/solo_spec.rb
index 686ae745d8..3f7c203c67 100644
--- a/spec/unit/application/solo_spec.rb
+++ b/spec/unit/application/solo_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: AJ Christensen (<aj@junglist.gen.nz>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -93,13 +93,13 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config
describe "when the json_attribs configuration option is specified" do
let(:json_attribs) { { "a" => "b" } }
- let(:config_fetcher) { double(Chef::ConfigFetcher, :fetch_json => json_attribs) }
+ let(:config_fetcher) { double(Chef::ConfigFetcher, fetch_json: json_attribs) }
let(:json_source) { "https://foo.com/foo.json" }
before do
Chef::Config[:json_attribs] = json_source
- expect(Chef::ConfigFetcher).to receive(:new).with(json_source).
- and_return(config_fetcher)
+ expect(Chef::ConfigFetcher).to receive(:new).with(json_source)
+ .and_return(config_fetcher)
end
it "reads the JSON attributes from the specified source" do
@@ -130,7 +130,7 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config
it "fetches the recipe_url first when both json_attribs and recipe_url are specified" do
json_attribs = { "a" => "b" }
- config_fetcher = instance_double("Chef::ConfigFetcher", :fetch_json => json_attribs)
+ config_fetcher = instance_double("Chef::ConfigFetcher", fetch_json: json_attribs)
Chef::Config[:json_attribs] = "https://foo.com/foo.json"
Chef::Config[:recipe_url] = "http://icanhas.cheezburger.com/lolcats"
@@ -203,19 +203,12 @@ Enable chef-client interval runs by setting `:client_fork = true` in your config
app.reconfigure
expect(ARGV.include?("--ez")).to be_falsey
end
-
- it "replaces -r with --recipe-url" do
- ARGV.push("-r", "http://junglist.gen.nz/recipes.tgz")
- app.reconfigure
- expect(ARGV.include?("-r")).to be_falsey
- expect(ARGV.include?("--recipe-url")).to be_truthy
- end
end
it "sets the repo path" do
expect(Chef::Config).to receive(:find_chef_repo_path).and_return("/var/chef")
app.reconfigure
- expect(Chef::Config.has_key?(:chef_repo_path)).to be_truthy
+ expect(Chef::Config.key?(:chef_repo_path)).to be_truthy
expect(Chef::Config[:chef_repo_path]).to eq ("/var/chef")
end
diff --git a/spec/unit/application_spec.rb b/spec/unit/application_spec.rb
index 7981748962..b8d7242466 100644
--- a/spec/unit/application_spec.rb
+++ b/spec/unit/application_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: AJ Christensen (<aj@junglist.gen.nz>)
# Author:: Mark Mzyk (mmzyk@chef.io)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -101,12 +101,13 @@ describe Chef::Application do
@app = Chef::Application.new
allow(@app).to receive(:parse_options).and_return(true)
+ allow(::File).to receive(:read).with("/proc/sys/crypto/fips_enabled").and_call_original
expect(Chef::Config).to receive(:export_proxies).and_return(true)
end
it "should parse the commandline options" do
expect(@app).to receive(:parse_options).and_return(true)
- @app.config[:config_file] = "/etc/chef/default.rb" #have a config file set, to prevent triggering error block
+ @app.config[:config_file] = "/etc/chef/default.rb" # have a config file set, to prevent triggering error block
@app.configure_chef
end
@@ -126,9 +127,9 @@ describe Chef::Application do
# force let binding to get evaluated or else we stub Pathname.new before we try to use it.
config_location_pathname
allow(Pathname).to receive(:new).with(config_location).and_return(config_location_pathname)
- expect(File).to receive(:read).
- with(config_location).
- and_return(config_content)
+ expect(File).to receive(:read)
+ .with(config_location)
+ .and_return(config_content)
end
it "should configure chef::config from a file" do
@@ -137,7 +138,7 @@ describe Chef::Application do
end
it "should merge the local config hash into chef::config" do
- #File.should_receive(:open).with("/etc/chef/default.rb").and_yield(@config_file)
+ # File.should_receive(:open).with("/etc/chef/default.rb").and_yield(@config_file)
@app.configure_chef
expect(Chef::Config.rspec_ran).to eq("true")
end
@@ -171,7 +172,7 @@ describe Chef::Application do
@app.config[:config_file] = "/etc/chef/notfound"
end
it "should use the passed in command line options and defaults" do
- expect(Chef::Config).to receive(:merge!)
+ expect(Chef::Config).to receive(:merge!).at_least(:once)
@app.configure_chef
end
end
@@ -392,11 +393,11 @@ describe Chef::Application do
def raises_informative_fatals_on_configure_chef
config_file_regexp = Regexp.new @app.config[:config_file]
- expect(Chef::Log).to receive(:fatal).
- with(/Configuration error/)
- expect(Chef::Log).to receive(:fatal).
- with(config_file_regexp).
- at_least(1).times
+ expect(Chef::Log).to receive(:fatal)
+ .with(/Configuration error/)
+ expect(Chef::Log).to receive(:fatal)
+ .with(config_file_regexp)
+ .at_least(1).times
@app.configure_chef
end
@@ -418,4 +419,68 @@ describe Chef::Application do
end
end
end
+
+ describe "merged config" do
+ class MyTestConfig < Chef::Config
+ extend Mixlib::Config
+
+ default :test_config_1, "config default"
+ default :test_config_2, "config default"
+ end
+
+ class MyAppClass < Chef::Application
+ # there's an implicit test here that mixlib-cli's separate_default_options is being inherited
+ option :test_config_2, long: "--test-config2 CONFIG", default: "cli default"
+ end
+
+ before(:each) do
+ MyTestConfig.reset
+ @original_argv = ARGV.dup
+ ARGV.clear
+ @app = MyAppClass.new
+ expect(@app).to receive(:chef_config).at_least(:once).and_return(MyTestConfig)
+ expect(Chef::ConfigFetcher).to receive(:new).and_return(fake_config_fetcher)
+ allow(@app).to receive(:log).and_return(instance_double(Mixlib::Log, warn: nil)) # ignorken
+ end
+
+ after(:each) do
+ ARGV.replace(@original_argv)
+ end
+
+ let(:fake_config_fetcher) { instance_double(Chef::ConfigFetcher, expanded_path: "/thisbetternotexist", "config_missing?": false, read_config: "" ) }
+
+ it "reading a mixlib-config default works" do
+ @app.parse_options
+ @app.load_config_file
+ expect(MyTestConfig[:test_config_1]).to eql("config default")
+ end
+
+ it "a mixlib-cli default overrides a mixlib-config default" do
+ @app.parse_options
+ @app.load_config_file
+ expect(MyTestConfig[:test_config_2]).to eql("cli default")
+ end
+
+ it "a set mixlib-config value overrides a mixlib-config default" do
+ expect(fake_config_fetcher).to receive(:read_config).and_return(%q{test_config_1 "config setting"})
+ @app.parse_options
+ @app.load_config_file
+ expect(MyTestConfig[:test_config_1]).to eql("config setting")
+ end
+
+ it "a set mixlib-config value overrides a mixlib-cli default" do
+ expect(fake_config_fetcher).to receive(:read_config).and_return(%q{test_config_2 "config setting"})
+ @app.parse_options
+ @app.load_config_file
+ expect(MyTestConfig[:test_config_2]).to eql("config setting")
+ end
+
+ it "a set mixlib-cli value overrides everything else" do
+ expect(fake_config_fetcher).to receive(:read_config).and_return(%q{test_config_2 "config setting"})
+ ARGV.replace("--test-config2 cli-setting".split)
+ @app.parse_options
+ @app.load_config_file
+ expect(MyTestConfig[:test_config_2]).to eql("cli-setting")
+ end
+ end
end
diff --git a/spec/unit/audit/audit_event_proxy_spec.rb b/spec/unit/audit/audit_event_proxy_spec.rb
index 820e670f1c..a9b27f238e 100644
--- a/spec/unit/audit/audit_event_proxy_spec.rb
+++ b/spec/unit/audit/audit_event_proxy_spec.rb
@@ -35,19 +35,19 @@ describe Chef::Audit::AuditEventProxy do
let(:description) { "poots" }
let(:group) do
- double("ExampleGroup", :parent_groups => parents,
- :description => description) end
- let(:notification) { double("Notification", :group => group) }
+ double("ExampleGroup", parent_groups: parents,
+ description: description) end
+ 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
- expect(Chef::Log).to receive(:debug).
- with("Entered \`control_group\` block named poots")
- expect(events).to receive(:control_group_started).
- with(description)
+ expect(Chef::Log).to receive(:trace)
+ .with("Entered \`control_group\` block named poots")
+ expect(events).to receive(:control_group_started)
+ .with(description)
audit_event_proxy.example_group_started(notification)
end
end
@@ -66,9 +66,9 @@ describe Chef::Audit::AuditEventProxy do
describe "#stop" do
let(:examples) { [] }
- let(:notification) { double("Notification", :examples => examples) }
+ let(:notification) { double("Notification", examples: examples) }
let(:exception) { nil }
- let(:example) { double("Example", :exception => exception) }
+ let(:example) { double("Example", exception: exception) }
let(:control_group_name) { "audit test" }
let(:control_data) { double("ControlData") }
@@ -87,14 +87,14 @@ describe Chef::Audit::AuditEventProxy do
let(:excpetion) { nil }
before do
- allow(audit_event_proxy).to receive(:build_control_from).
- with(example).
- and_return([control_group_name, control_data])
+ allow(audit_event_proxy).to receive(:build_control_from)
+ .with(example)
+ .and_return([control_group_name, control_data])
end
it "notifies events" do
- expect(events).to receive(:control_example_success).
- with(control_group_name, control_data)
+ expect(events).to receive(:control_example_success)
+ .with(control_group_name, control_data)
audit_event_proxy.stop(notification)
end
end
@@ -105,14 +105,14 @@ describe Chef::Audit::AuditEventProxy do
let(:exception) { double("ExpectationNotMet") }
before do
- allow(audit_event_proxy).to receive(:build_control_from).
- with(example).
- and_return([control_group_name, control_data])
+ allow(audit_event_proxy).to receive(:build_control_from)
+ .with(example)
+ .and_return([control_group_name, control_data])
end
it "notifies events" do
- expect(events).to receive(:control_example_failure).
- with(control_group_name, control_data, exception)
+ expect(events).to receive(:control_example_failure)
+ .with(control_group_name, control_data, exception)
audit_event_proxy.stop(notification)
end
end
@@ -122,29 +122,29 @@ describe Chef::Audit::AuditEventProxy do
let(:examples) { [example] }
let(:example) do
- double("Example", :metadata => metadata,
- :description => example_description,
- :full_description => full_description, :exception => nil) end
+ double("Example", metadata: metadata,
+ description: example_description,
+ full_description: full_description, exception: nil) end
let(:metadata) do
{
- :described_class => described_class,
- :example_group => example_group,
- :line_number => line,
+ described_class: described_class,
+ example_group: example_group,
+ line_number: line,
}
end
let(:example_group) do
{
- :description => group_description,
- :parent_example_group => parent_group,
+ description: group_description,
+ parent_example_group: parent_group,
}
end
let(:parent_group) do
{
- :description => control_group_name,
- :parent_example_group => nil,
+ description: control_group_name,
+ parent_example_group: nil,
}
end
@@ -152,12 +152,12 @@ describe Chef::Audit::AuditEventProxy do
let(:control_data) do
{
- :name => example_description,
- :desc => full_description,
- :resource_type => resource_type,
- :resource_name => resource_name,
- :context => context,
- :line_number => line,
+ name: example_description,
+ desc: full_description,
+ resource_type: resource_type,
+ resource_name: resource_name,
+ context: context,
+ line_number: line,
}
end
@@ -165,17 +165,17 @@ describe Chef::Audit::AuditEventProxy do
before do
if described_class
- allow(described_class).to receive(:instance_variable_get).
- with(:@name).
- and_return(resource_name)
- allow(described_class.class).to receive(:name).
- and_return(described_class.class)
+ allow(described_class).to receive(:instance_variable_get)
+ .with(:@name)
+ .and_return(resource_name)
+ allow(described_class.class).to receive(:name)
+ .and_return(described_class.class)
end
end
it "returns the controls block name and example metadata for reporting" do
- expect(events).to receive(:control_example_success).
- with(control_group_name, control_data)
+ expect(events).to receive(:control_example_success)
+ .with(control_group_name, control_data)
audit_event_proxy.stop(notification)
end
end
@@ -227,7 +227,7 @@ describe Chef::Audit::AuditEventProxy do
# Metadata fields
let(:described_class) do
double("Serverspec::Type::Port",
- :class => "Serverspec::Type::Port", :name => resource_name) end
+ class: "Serverspec::Type::Port", name: resource_name) end
# Control data fields
let(:resource_type) { "Port" }
@@ -288,20 +288,20 @@ describe Chef::Audit::AuditEventProxy do
# Metadata parts
let(:described_class) do
double("Serverspec::Type::File",
- :class => "Serverspec::Type::File", :name => resource_name) end
+ class: "Serverspec::Type::File", name: resource_name) end
# Example group parts
let(:parent_group) do
{
- :description => outer_group_description,
- :parent_example_group => control_group,
+ description: outer_group_description,
+ parent_example_group: control_group,
}
end
let(:control_group) do
{
- :description => control_group_name,
- :parent_example_group => nil,
+ description: control_group_name,
+ parent_example_group: nil,
}
end
diff --git a/spec/unit/audit/audit_reporter_spec.rb b/spec/unit/audit/audit_reporter_spec.rb
index cf916266d8..db065db923 100644
--- a/spec/unit/audit/audit_reporter_spec.rb
+++ b/spec/unit/audit/audit_reporter_spec.rb
@@ -2,7 +2,7 @@
# Author:: Tyler Ball (<tball@chef.io>)
# Author:: Claire McQuin (<claire@chef.io>)
#
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,18 +24,18 @@ describe Chef::Audit::AuditReporter do
let(:rest) { double("rest") }
let(:reporter) { described_class.new(rest) }
- let(:node) { double("node", :name => "sofreshsoclean") }
+ let(:node) { double("node", name: "sofreshsoclean") }
let(:run_id) { 0 }
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) do
- instance_double(Chef::RunStatus, :node => node, :run_id => run_id,
- :start_time => start_time, :end_time => end_time) end
+ instance_double(Chef::RunStatus, node: node, run_id: run_id,
+ start_time: start_time, end_time: end_time) end
describe "#audit_phase_start" do
- it "notifies audit phase start to debug log" do
- expect(Chef::Log).to receive(:debug).with(/Audit Reporter starting/)
+ it "notifies audit phase start to trace log" do
+ expect(Chef::Log).to receive(:trace).with(/Audit Reporter starting/)
reporter.audit_phase_start(run_status)
end
@@ -79,17 +79,17 @@ describe Chef::Audit::AuditReporter do
"X-Ops-Audit-Report-Protocol-Version" => Chef::Audit::AuditReporter::PROTOCOL_VERSION,
}
- expect(rest).to receive(:post).
- with("controls", run_data, headers)
+ expect(rest).to receive(:post)
+ .with("controls", run_data, headers)
reporter.run_completed(node)
end
context "when audit phase failed" do
let(:audit_error) do
- double("AuditError", :class => "Chef::Exceptions::AuditError",
- :message => "Audit phase failed with error message: derpderpderp",
- :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) end
+ double("AuditError", class: "Chef::Exceptions::AuditError",
+ message: "Audit phase failed with error message: derpderpderp",
+ backtrace: ["/path/recipe.rb:57", "/path/library.rb:106"]) end
before do
reporter.instance_variable_set(:@audit_phase_error, audit_error)
@@ -99,10 +99,10 @@ describe Chef::Audit::AuditReporter do
reporter.run_completed(node)
expect(run_data).to have_key(:error)
expect(run_data).to have_key(:error)
- expect(run_data[:error]).to eq <<-EOM.strip!
-Chef::Exceptions::AuditError: Audit phase failed with error message: derpderpderp
-/path/recipe.rb:57
-/path/library.rb:106
+ expect(run_data[:error]).to eq <<~EOM.strip!
+ Chef::Exceptions::AuditError: Audit phase failed with error message: derpderpderp
+ /path/recipe.rb:57
+ /path/library.rb:106
EOM
end
@@ -123,11 +123,11 @@ EOM
context "the error is an http error" do
- let(:response) { double("response", :code => code) }
+ let(:response) { double("response", code: code) }
before do
- expect(Chef::Log).to receive(:debug).with(/Sending audit report/)
- expect(Chef::Log).to receive(:debug).with(/Audit Report/)
+ expect(Chef::Log).to receive(:trace).with(/Sending audit report/)
+ expect(Chef::Log).to receive(:trace).with(/Audit Report/)
allow(error).to receive(:response).and_return(response)
expect(error).to receive(:respond_to?).with(:response).and_return(true)
end
@@ -137,7 +137,7 @@ EOM
let(:code) { "404" }
it "logs that the server doesn't support audit reporting" do
- expect(Chef::Log).to receive(:debug).with(/Server doesn't support audit reporting/)
+ expect(Chef::Log).to receive(:trace).with(/Server doesn't support audit reporting/)
reporter.run_completed(node)
end
end
@@ -145,12 +145,12 @@ EOM
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).
- and_return(true)
- expect(Chef::FileCache).to receive(:load).
- with("failed-audit-data.json", false).
- and_return(true)
+ expect(Chef::FileCache).to receive(:store)
+ .with("failed-audit-data.json", an_instance_of(String), 0640)
+ .and_return(true)
+ expect(Chef::FileCache).to receive(:load)
+ .with("failed-audit-data.json", false)
+ .and_return(true)
expect(Chef::Log).to receive(:error).with(/Failed to post audit report to server/)
reporter.run_completed(node)
end
@@ -184,9 +184,9 @@ EOM
context "when reporting url fatals are enabled" do
before do
- allow(Chef::Config).to receive(:[]).
- with(:enable_reporting_url_fatals).
- and_return(true)
+ allow(Chef::Config).to receive(:[])
+ .with(:enable_reporting_url_fatals)
+ .and_return(true)
end
it "raises the error" do
@@ -203,12 +203,12 @@ EOM
context "when auditing is not enabled" do
before do
- allow(Chef::Log).to receive(:debug)
+ allow(Chef::Log).to receive(:trace)
end
it "doesn't send reports" do
expect(reporter).to receive(:auditing_enabled?).and_return(false)
- expect(Chef::Log).to receive(:debug).with("Audit Reports are disabled. Skipping sending reports.")
+ expect(Chef::Log).to receive(:trace).with("Audit Reports are disabled. Skipping sending reports.")
reporter.run_completed(node)
end
@@ -217,13 +217,13 @@ EOM
context "when the run fails before audits" do
before do
- allow(Chef::Log).to receive(:debug)
+ allow(Chef::Log).to receive(:trace)
end
it "doesn't send reports" do
expect(reporter).to receive(:auditing_enabled?).and_return(true)
expect(reporter).to receive(:run_status).and_return(nil)
- expect(Chef::Log).to receive(:debug).with("Run failed before audit mode was initialized, not sending audit report to server")
+ expect(Chef::Log).to receive(:trace).with("Run failed before audit mode was initialized, not sending audit report to server")
reporter.run_completed(node)
end
@@ -236,14 +236,14 @@ EOM
let(:run_data) { audit_data.to_hash }
let(:audit_error) do
- double("AuditError", :class => "Chef::Exceptions::AuditError",
- :message => "Audit phase failed with error message: derpderpderp",
- :backtrace => ["/path/recipe.rb:57", "/path/library.rb:106"]) end
+ double("AuditError", class: "Chef::Exceptions::AuditError",
+ message: "Audit phase failed with error message: derpderpderp",
+ backtrace: ["/path/recipe.rb:57", "/path/library.rb:106"]) end
let(:run_error) do
- double("RunError", :class => "Chef::Exceptions::RunError",
- :message => "This error shouldn't be reported.",
- :backtrace => ["fix it", "fix it", "fix it"]) end
+ double("RunError", class: "Chef::Exceptions::RunError",
+ message: "This error shouldn't be reported.",
+ backtrace: ["fix it", "fix it", "fix it"]) end
before do
allow(reporter).to receive(:auditing_enabled?).and_return(true)
@@ -269,10 +269,10 @@ EOM
expect(rest).to receive(:post)
reporter.run_failed(run_error)
expect(run_data).to have_key(:error)
- expect(run_data[:error]).to eq <<-EOM.strip!
-Chef::Exceptions::AuditError: Audit phase failed with error message: derpderpderp
-/path/recipe.rb:57
-/path/library.rb:106
+ expect(run_data[:error]).to eq <<~EOM.strip!
+ Chef::Exceptions::AuditError: Audit phase failed with error message: derpderpderp
+ /path/recipe.rb:57
+ /path/library.rb:106
EOM
end
end
@@ -282,10 +282,10 @@ EOM
let(:control_group_foo) do
instance_double(Chef::Audit::ControlGroupData,
- :metadata => double("foo metadata")) end
+ metadata: double("foo metadata")) end
let(:control_group_bar) do
instance_double(Chef::Audit::ControlGroupData,
- :metadata => double("bar metadata")) end
+ metadata: double("bar metadata")) end
let(:ordered_control_groups) do
{
@@ -296,11 +296,11 @@ EOM
let(:audit_data) do
instance_double(Chef::Audit::AuditData,
- :add_control_group => true) end
+ add_control_group: true) end
let(:run_context) do
instance_double(Chef::RunContext,
- :audits => ordered_control_groups) end
+ audits: ordered_control_groups) end
before do
allow(reporter).to receive(:ordered_control_groups).and_return(ordered_control_groups)
@@ -313,13 +313,13 @@ EOM
describe "#audit_phase_complete" do
include_context "audit data"
- it "notifies audit phase finished to debug log" do
- expect(Chef::Log).to receive(:debug).with(/Audit Reporter completed/)
+ it "notifies audit phase finished to trace log" do
+ expect(Chef::Log).to receive(:trace).with(/Audit Reporter completed/)
reporter.audit_phase_complete("Output from audit mode")
end
it "collects audit data" do
- ordered_control_groups.each do |_name, group|
+ ordered_control_groups.each_value do |group|
expect(audit_data).to receive(:add_control_group).with(group)
end
reporter.audit_phase_complete("Output from audit mode")
@@ -331,13 +331,13 @@ EOM
let(:error) { double("Exception") }
- it "notifies audit phase failed to debug log" do
- expect(Chef::Log).to receive(:debug).with(/Audit Reporter failed/)
+ it "notifies audit phase failed to trace log" do
+ expect(Chef::Log).to receive(:trace).with(/Audit Reporter failed/)
reporter.audit_phase_failed(error, "Output from audit mode")
end
it "collects audit data" do
- ordered_control_groups.each do |_name, group|
+ ordered_control_groups.each_value do |group|
expect(audit_data).to receive(:add_control_group).with(group)
end
reporter.audit_phase_failed(error, "Output from audit mode")
@@ -350,31 +350,27 @@ EOM
let(:name) { "bat" }
let(:control_group) do
instance_double(Chef::Audit::ControlGroupData,
- :metadata => double("metadata")) end
+ metadata: double("metadata")) end
before do
- allow(Chef::Audit::ControlGroupData).to receive(:new).
- with(name, control_group.metadata).
- and_return(control_group)
+ allow(Chef::Audit::ControlGroupData).to receive(:new)
+ .with(name, control_group.metadata)
+ .and_return(control_group)
end
it "stores the control group" do
- expect(ordered_control_groups).to receive(:has_key?).with(name).and_return(false)
+ expect(ordered_control_groups).to receive(:key?).with(name).and_return(false)
allow(run_context.audits).to receive(:[]).with(name).and_return(control_group)
- expect(ordered_control_groups).to receive(:store).
- with(name, control_group).
- and_call_original
+ expect(ordered_control_groups).to receive(:store)
+ .with(name, control_group)
+ .and_call_original
reporter.control_group_started(name)
- # stubbed :has_key? above, which is used by the have_key matcher,
- # so instead we check the response to Hash's #key? because luckily
- # #key? does not call #has_key?
- expect(ordered_control_groups.key?(name)).to be true
expect(ordered_control_groups[name]).to eq control_group
end
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(ordered_control_groups).to receive(:key?).with(name).and_return(true)
expect { reporter.control_group_started(name) }.to raise_error(Chef::Exceptions::AuditControlGroupDuplicate)
end
end
@@ -397,11 +393,11 @@ EOM
let(:name) { "bar" }
let(:example_data) { double("example data") }
- let(:error) { double("Exception", :message => "oopsie") }
+ let(:error) { double("Exception", message: "oopsie") }
it "notifies the control group the example failed" do
- expect(control_group_bar).to receive(:example_failure).
- with(example_data, error.message)
+ expect(control_group_bar).to receive(:example_failure)
+ .with(example_data, error.message)
reporter.control_example_failure(name, example_data, error)
end
end
@@ -410,9 +406,9 @@ EOM
shared_examples "enabled?" do |true_or_false|
it "returns #{true_or_false}" do
- expect(Chef::Config).to receive(:[]).
- with(:audit_mode).
- and_return(audit_setting)
+ expect(Chef::Config).to receive(:[])
+ .with(:audit_mode)
+ .and_return(audit_setting)
expect(reporter.auditing_enabled?).to be true_or_false
end
end
diff --git a/spec/unit/audit/control_group_data_spec.rb b/spec/unit/audit/control_group_data_spec.rb
index ea4ac260f9..82af77dcea 100644
--- a/spec/unit/audit/control_group_data_spec.rb
+++ b/spec/unit/audit/control_group_data_spec.rb
@@ -72,8 +72,8 @@ describe Chef::Audit::AuditData do
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] }
@@ -174,11 +174,11 @@ describe Chef::Audit::ControlGroupData do
let(:control_data) do
{
- :name => name,
- :resource_type => resource_type,
- :resource_name => resource_name,
- :context => context,
- :line_number => line_number,
+ name: name,
+ resource_type: resource_type,
+ resource_name: resource_name,
+ context: context,
+ line_number: line_number,
}
end
@@ -193,11 +193,11 @@ describe Chef::Audit::ControlGroupData do
context: context, line_number: line_number) end
before do
- allow(Chef::Audit::ControlData).to receive(:new).
- with(name: name, resource_type: resource_type,
+ allow(Chef::Audit::ControlData).to receive(:new)
+ .with(name: name, resource_type: resource_type,
resource_name: resource_name, context: context,
- line_number: line_number).
- and_return(control)
+ line_number: line_number)
+ .and_return(control)
end
end
@@ -434,22 +434,22 @@ describe Chef::Audit::ControlGroupData do
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) do
double("control 1",
- :line_number => control_hash_1[:line_number],
- :to_hash => control_hash_1) end
+ line_number: control_hash_1[:line_number],
+ to_hash: control_hash_1) end
let(:control_2) do
double("control 2",
- :line_number => control_hash_2[:line_number],
- :to_hash => control_hash_2) end
+ line_number: control_hash_2[:line_number],
+ to_hash: control_hash_2) end
let(:control_3) do
double("control 3",
- :line_number => control_hash_3[:line_number],
- :to_hash => control_hash_3) end
+ line_number: control_hash_3[:line_number],
+ to_hash: control_hash_3) end
let(:control_list) { [control_1, control_2, control_3] }
let(:ordered_control_hashes) { [control_hash_2, control_hash_1, control_hash_3] }
diff --git a/spec/unit/audit/runner_spec.rb b/spec/unit/audit/runner_spec.rb
index 4c03cab1d3..902ede62ed 100644
--- a/spec/unit/audit/runner_spec.rb
+++ b/spec/unit/audit/runner_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Audit::Runner do
include RSpec::Support::InSubProcess
let(:events) { double("events") }
- let(:run_context) { instance_double(Chef::RunContext, :events => events) }
+ let(:run_context) { instance_double(Chef::RunContext, events: events) }
let(:runner) { Chef::Audit::Runner.new(run_context) }
around(:each) do |ex|
@@ -89,7 +89,7 @@ describe Chef::Audit::Runner do
describe "#register_control_groups" do
let(:audits) { [] }
- let(:run_context) { instance_double(Chef::RunContext, :audits => audits) }
+ let(:run_context) { instance_double(Chef::RunContext, audits: audits) }
it "adds the control group aliases" do
runner.send(:register_control_groups)
diff --git a/spec/unit/chef_class_spec.rb b/spec/unit/chef_class_spec.rb
index 21987c01ab..2f370388fa 100644
--- a/spec/unit/chef_class_spec.rb
+++ b/spec/unit/chef_class_spec.rb
@@ -107,4 +107,124 @@ describe "Chef class" do
end.to raise_error(Chef::Exceptions::InvalidEventType)
end
end
+
+ describe "Deprecation system" do
+ context "with treat_deprecation_warnings_as_errors false" do
+ before { Chef::Config[:treat_deprecation_warnings_as_errors] = false }
+
+ it "displays a simple deprecation warning" do
+ expect(Chef::Log).to receive(:warn).with(%r{spec/unit/chef_class_spec\.rb.*?I'm a little teapot.*?Please see}m)
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ end
+
+ it "allows silencing all warnings" do
+ Chef::Config[:silence_deprecation_warnings] = true
+ expect(Chef::Log).to_not receive(:warn)
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.")
+ Chef.deprecated(:generic, "This is my handle.")
+ end
+
+ it "allows silencing specific types" do
+ Chef::Config[:silence_deprecation_warnings] = [:internal_api]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.")
+ Chef.deprecated(:generic, "This is my handle.")
+ end
+
+ it "allows silencing specific IDs" do
+ Chef::Config[:silence_deprecation_warnings] = [0]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.")
+ Chef.deprecated(:generic, "This is my handle.")
+ end
+
+ it "allows silencing specific IDs using the CHEF- syntax" do
+ Chef::Config[:silence_deprecation_warnings] = ["CHEF-0"]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.")
+ Chef.deprecated(:generic, "This is my handle.")
+ end
+
+ it "allows silencing specific IDs using the chef- syntax" do
+ Chef::Config[:silence_deprecation_warnings] = ["chef-0"]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.")
+ Chef.deprecated(:generic, "This is my handle.")
+ end
+
+ it "allows silencing specific lines" do
+ Chef::Config[:silence_deprecation_warnings] = ["chef_class_spec.rb:#{__LINE__ + 4}"]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:generic, "Short and stout.")
+ Chef.deprecated(:internal_api, "This is my handle.")
+ end
+
+ it "allows silencing all via inline comments" do
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:generic, "Short and stout.") # chef:silence_deprecation
+ Chef.deprecated(:internal_api, "This is my handle.")
+ end
+
+ it "allows silencing specific types via inline comments" do
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:generic, "Short and stout.") # chef:silence_deprecation:generic
+ Chef.deprecated(:internal_api, "This is my handle.")
+ end
+
+ it "does not silence via inline comments when the types don't match" do
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/Short and stout/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:internal_api, "Short and stout.") # chef:silence_deprecation:generic
+ Chef.deprecated(:internal_api, "This is my handle.")
+ end
+
+ it "allows silencing all via inline comments with other stuff in the comment" do
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my handle/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:generic, "Short and stout.") # rubocop:something chef:silence_deprecation other stuff
+ Chef.deprecated(:internal_api, "This is my handle.")
+ end
+
+ it "handles multiple silence configurations at the same time" do
+ Chef::Config[:silence_deprecation_warnings] = ["exit_code", "chef_class_spec.rb:#{__LINE__ + 6}"]
+ expect(Chef::Log).to receive(:warn).with(/I'm a little teapot/).once
+ expect(Chef::Log).to receive(:warn).with(/This is my spout/).once
+ expect(Chef::Log).to receive(:warn).with(/Hear me shout/).once
+ Chef.deprecated(:generic, "I'm a little teapot.")
+ Chef.deprecated(:generic, "Short and stout.") # chef:silence_deprecation
+ Chef.deprecated(:internal_api, "This is my handle.")
+ Chef.deprecated(:internal_api, "This is my spout.")
+ Chef.deprecated(:exit_code, "When I get all steamed up.")
+ Chef.deprecated(:generic, "Hear me shout.")
+ end
+ end
+
+ context "with treat_deprecation_warnings_as_errors true" do
+ # This is already turned on globally for Chef's unit tests, but just for clarity do it here too.
+ before { Chef::Config[:treat_deprecation_warnings_as_errors] = true }
+
+ it "displays a simple deprecation error" do
+ expect(Chef::Log).to receive(:error).with(%r{spec/unit/chef_class_spec\.rb.*?I'm a little teapot.*?Please see}m)
+ expect { Chef.deprecated(:generic, "I'm a little teapot.") }.to raise_error(/I'm a little teapot./)
+ end
+ end
+ end
end
diff --git a/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb b/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb
new file mode 100644
index 0000000000..60cd5c6cb7
--- /dev/null
+++ b/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb
@@ -0,0 +1,82 @@
+#
+# Author:: Sandra Tiffin (<sandi.tiffin@gmail.com>)
+# Copyright:: Copyright 2014-2016, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb"
+
+class TestDataBag < Mash
+ attr_accessor :name
+
+ def initialize(bag_name)
+ @name = bag_name
+ end
+end
+
+class TestDataBagItem < Mash
+ attr_accessor :name, :parent
+
+ def path_for_printing
+ "/some/path"
+ end
+
+ def initialize(bag_name, item_name)
+ @name = "#{item_name}.json"
+ @parent = TestDataBag.new(bag_name)
+ end
+end
+
+describe Chef::ChefFS::DataHandler::DataBagItemDataHandler do
+ let(:handler) { described_class.new }
+
+ describe "#verify_integrity" do
+ context "json id does not match data bag item name" do
+ let(:entry) { TestDataBagItem.new("luggage", "bag") }
+ let(:object) do
+ { "raw_data" => { "id" => "duffel" } }
+ end
+ it "rejects the data bag item name" do
+ expect { |b| handler.verify_integrity(object, entry, &b) }.to yield_with_args
+ end
+ end
+
+ context "using a reserved word for the data bag name" do
+ %w{node role environment client}.each do |reserved_word|
+ let(:entry) { TestDataBagItem.new(reserved_word, "bag") }
+ let(:object) do
+ { "raw_data" => { "id" => "bag" } }
+ end
+ it "rejects the data bag name '#{reserved_word}'" do
+ expect { |b| handler.verify_integrity(object, entry, &b) }.to yield_with_args
+ end
+ end
+ end
+
+ context "using a reserved word as part of the data bag name" do
+ %w{xnode rolex xenvironmentx xclientx}.each do |bag_name|
+ let(:entry) { TestDataBagItem.new(bag_name.to_s, "bag") }
+ let(:object) do
+ { "raw_data" => { "id" => "bag" } }
+ end
+ it "allows the data bag name '#{bag_name}'" do
+ expect(handler.verify_integrity(object, entry)).to be_nil
+ end
+ end
+ end
+
+ end
+end
diff --git a/spec/unit/chef_fs/data_handler/data_handler_base_spec.rb b/spec/unit/chef_fs/data_handler/data_handler_base_spec.rb
new file mode 100644
index 0000000000..b4cb5a33f2
--- /dev/null
+++ b/spec/unit/chef_fs/data_handler/data_handler_base_spec.rb
@@ -0,0 +1,65 @@
+#
+# Author:: Jeremy Miller (<jm@chef.io>)
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "lib/chef/chef_fs/data_handler/data_handler_base"
+
+describe Chef::ChefFS::DataHandler::DataHandlerBase do
+ describe "#normalize_hash" do
+ let(:some_item) do
+ { "name" => "grizzly",
+ "gender" => "female",
+ "age" => 3,
+ "food" => "honey",
+ }
+ end
+
+ let(:item_defaults) do
+ { "family" => "ursidae",
+ "hibernate" => true,
+ "food" => "berries",
+ "avg_lifespan_years" => 22,
+ }
+ end
+
+ let(:normalized) do
+ { "name" => "grizzly",
+ "gender" => "female",
+ "family" => "ursidae",
+ "hibernate" => true,
+ "avg_lifespan_years" => 22,
+ "age" => 3,
+ "food" => "honey",
+ }
+ end
+
+ let(:handler) { described_class.new }
+
+ it "normalizes the Hash, filling in default values" do
+ expect(handler.normalize_hash(some_item, item_defaults)).to eq(normalized)
+ end
+
+ it "prefers already existing values over default values" do
+ expect(handler.normalize_hash(some_item, item_defaults)["food"]).to eq("honey")
+ end
+
+ it "handles being passed a nil value instead of Hash" do
+ expect(handler.normalize_hash(nil, item_defaults)).to eq(item_defaults)
+ end
+ end
+end
diff --git a/spec/unit/chef_fs/diff_spec.rb b/spec/unit/chef_fs/diff_spec.rb
index d946fcb9e7..229a48c2db 100644
--- a/spec/unit/chef_fs/diff_spec.rb
+++ b/spec/unit/chef_fs/diff_spec.rb
@@ -28,62 +28,62 @@ def remove_os_differences(diff)
diff.gsub(/^@@ -\d(,\d)? \+\d(,\d)? @@/, "CONTEXT_LINE_NUMBERS")
end
-describe "diff", :uses_diff => true do
+describe "diff", uses_diff: true do
include FileSystemSupport
context "with two filesystems with all types of difference" do
let(:a) do
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_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,
+ 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/)
end
let(:b) do
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_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 => {},
+ 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/)
end
it "Chef::ChefFS::CommandLine.diff_print(/)" do
diff --git a/spec/unit/chef_fs/file_pattern_spec.rb b/spec/unit/chef_fs/file_pattern_spec.rb
index c4d076ef90..58cdbb28c2 100644
--- a/spec/unit/chef_fs/file_pattern_spec.rb
+++ b/spec/unit/chef_fs/file_pattern_spec.rb
@@ -157,7 +157,7 @@ describe Chef::ChefFS::FilePattern do
end
end
- context 'with simple pattern "a\*\b"', :skip => (Chef::Platform.windows?) do
+ context 'with simple pattern "a\*\b"', skip: (Chef::Platform.windows?) do
let(:pattern) { Chef::ChefFS::FilePattern.new('a\*\b') }
it "match?" do
expect(pattern.match?("a*b")).to be_truthy
@@ -264,7 +264,7 @@ describe Chef::ChefFS::FilePattern do
end
end
- context 'with star pattern "/abc/d[a-z][0-9]f/ghi"', :skip => (Chef::Platform.windows?) do
+ context 'with star pattern "/abc/d[a-z][0-9]f/ghi"', skip: (Chef::Platform.windows?) do
let(:pattern) { Chef::ChefFS::FilePattern.new("/abc/d[a-z][0-9]f/ghi") }
it "match?" do
expect(pattern.match?("/abc/de1f/ghi")).to be_truthy
diff --git a/spec/unit/chef_fs/file_system/repository/directory_spec.rb b/spec/unit/chef_fs/file_system/repository/directory_spec.rb
index 6e53e52966..5b2a0a47b8 100644
--- a/spec/unit/chef_fs/file_system/repository/directory_spec.rb
+++ b/spec/unit/chef_fs/file_system/repository/directory_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Thom May (<thom@chef.io>)
-# Copyright:: Copyright 2012-2016, Chef Software Inc.
+# Copyright:: Copyright 2012-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,7 +22,7 @@ require "chef/chef_fs/file_system/base_fs_object"
require "chef/chef_fs/file_system/exceptions"
require "chef/chef_fs/file_system/nonexistent_fs_object"
-CHILD_FILES = %w{ test1.json test2.json skip test3.json skip2 test4 }
+CHILD_FILES = %w{ test1.json test2.json skip test3.json skip2 test4 }.freeze
class TestDirectory < Chef::ChefFS::FileSystem::Repository::Directory
def make_child_entry(name)
@@ -88,7 +88,7 @@ describe Chef::ChefFS::FileSystem::Repository::Directory do
end
it "returns a non existent object otherwise" do
- file_double = instance_double(TestFile, :name_valid? => false)
+ file_double = instance_double(TestFile, name_valid?: false)
expect(TestFile).to receive(:new).with("test_child", test_directory).and_return(file_double)
expect(test_directory.child("test_child")).to be_an_instance_of(Chef::ChefFS::FileSystem::NonexistentFSObject)
end
@@ -152,7 +152,7 @@ describe Chef::ChefFS::FileSystem::Repository::Directory do
end
after do
- FileUtils.rmdir(tmp_dir)
+ FileUtils.rm_rf(tmp_dir)
end
end
diff --git a/spec/unit/chef_fs/file_system_spec.rb b/spec/unit/chef_fs/file_system_spec.rb
index 5c74729557..fed468f2cd 100644
--- a/spec/unit/chef_fs/file_system_spec.rb
+++ b/spec/unit/chef_fs/file_system_spec.rb
@@ -57,17 +57,17 @@ describe Chef::ChefFS::FileSystem do
context "with a populated filesystem" do
let(:fs) do
memory_fs("", {
- :a => {
- :aa => {
- :c => "",
- :zz => "",
+ a: {
+ aa: {
+ c: "",
+ zz: "",
},
- :ab => {
- :c => "",
+ ab: {
+ c: "",
},
},
- :x => "",
- :y => {},
+ x: "",
+ y: {},
})
end
context "list" do
@@ -140,7 +140,7 @@ describe Chef::ChefFS::FileSystem do
it "is empty /y" do
expect(Chef::ChefFS::FileSystem.resolve_path(fs, "/y").empty?).to be true
end
- it 'is not a directory and can\'t be tested /x' do
+ it "is not a directory and can't be tested /x" do
expect { Chef::ChefFS::FileSystem.resolve_path(fs, "/x").empty? }.to raise_error(NoMethodError)
end
end
diff --git a/spec/unit/chef_fs/parallelizer.rb b/spec/unit/chef_fs/parallelizer.rb
index 84637f7283..cbfa3402fa 100644
--- a/spec/unit/chef_fs/parallelizer.rb
+++ b/spec/unit/chef_fs/parallelizer.rb
@@ -20,7 +20,7 @@ describe Chef::ChefFS::Parallelizer do
end
def parallelize(inputs, options = {}, &block)
- parallelizer.parallelize(inputs, { :main_thread_processing => false }.merge(options), &block)
+ parallelizer.parallelize(inputs, { main_thread_processing: false }.merge(options), &block)
end
it "parallel_do creates unordered output as soon as it is available" do
@@ -35,14 +35,14 @@ describe Chef::ChefFS::Parallelizer do
context "With :ordered => false (unordered output)" do
it "An empty input produces an empty output" do
- expect(parallelize([], :ordered => false) do
+ expect(parallelize([], ordered: false) do
sleep 10
end.to_a).to eql([])
expect(elapsed_time).to be < 0.1
end
it "10 sleep(0.2)s complete within 0.5 seconds" do
- expect(parallelize(1.upto(10), :ordered => false) do |i|
+ expect(parallelize(1.upto(10), ordered: false) do |i|
sleep 0.2
"x"
end.to_a).to eq(%w{x x x x x x x x x x})
@@ -50,7 +50,7 @@ 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
@@ -64,7 +64,7 @@ describe Chef::ChefFS::Parallelizer do
input = TestEnumerable.new(0.5, 0.3, 0.1) do
raise "hi"
end
- enum = parallelize(input, :ordered => false) { |x| sleep(x); x }
+ enum = parallelize(input, ordered: false) { |x| sleep(x); x }
results = []
expect { enum.each { |value| results << value } }.to raise_error "hi"
expect(results).to eq([ 0.1, 0.3, 0.5 ])
@@ -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"
@@ -114,7 +114,7 @@ describe Chef::ChefFS::Parallelizer do
end
it "10 sleep(0.2)s complete within 0.5 seconds" do
- expect(parallelize(1.upto(10), :ordered => true) do |i|
+ expect(parallelize(1.upto(10), ordered: true) do |i|
sleep 0.2
"x"
end.to_a).to eq(%w{x x x x x x x x x x})
@@ -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"
@@ -205,7 +205,7 @@ describe Chef::ChefFS::Parallelizer do
started = false
@occupying_job_finished = occupying_job_finished = [ false ]
@thread = Thread.new do
- parallelizer.parallelize([0], :main_thread_processing => false) do |x|
+ parallelizer.parallelize([0], main_thread_processing: false) do |x|
started = true
sleep(0.3)
occupying_job_finished[0] = true
@@ -229,7 +229,7 @@ describe Chef::ChefFS::Parallelizer do
end
it "parallelize with :main_thread_processing = false waits for the job to finish" do
- expect(parallelizer.parallelize([1], :main_thread_processing => false) do |x|
+ expect(parallelizer.parallelize([1], main_thread_processing: false) do |x|
sleep(0.1)
x + 1
end.to_a).to eq([ 2 ])
@@ -434,7 +434,7 @@ describe Chef::ChefFS::Parallelizer do
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
diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb
index d348c24385..4f9d66d776 100644
--- a/spec/unit/client_spec.rb
+++ b/spec/unit/client_spec.rb
@@ -38,12 +38,23 @@ describe Chef::Client do
end
it "runs ohai with only the minimum required plugins" do
- expected_filter = %w{fqdn machinename hostname platform platform_version os os_version}
+ expected_filter = %w{fqdn machinename hostname platform platform_version ohai_time os os_version}
expect(ohai_system).to receive(:all_plugins).with(expected_filter)
client.run_ohai
end
end
+ context "when Ohai tells us to fail" do
+ it "fails" do
+ ohai_system = Ohai::System.new
+ module Ohai::Exceptions
+ class CriticalPluginFailure < Error; end
+ end
+ expect(ohai_system).to receive(:all_plugins) { raise Ohai::Exceptions::CriticalPluginFailure }
+ expect { client.run_ohai }.to raise_error(SystemExit)
+ end
+ end
+
describe "authentication protocol selection" do
context "when FIPS is disabled" do
before do
@@ -168,12 +179,12 @@ describe Chef::Client do
context "when an override run list is given" do
it "permits spaces in overriding run list" do
- Chef::Client.new(nil, :override_runlist => "role[a], role[b]")
+ Chef::Client.new(nil, override_runlist: "role[a], role[b]")
end
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
@@ -181,9 +192,9 @@ 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], version_class: Chef::CookbookManifestVersions).and_return(http_cookbook_sync)
- expect(http_cookbook_sync).to receive(:post).
- with("environments/_default/cookbook_versions", { :run_list => ["override_recipe"] }).
- and_return({})
+ expect(http_cookbook_sync).to receive(:post)
+ .with("environments/_default/cookbook_versions", { run_list: ["override_recipe"] })
+ .and_return({})
end
def stub_for_node_save
@@ -207,7 +218,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
@@ -215,9 +226,9 @@ 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], version_class: Chef::CookbookManifestVersions).and_return(http_cookbook_sync)
- expect(http_cookbook_sync).to receive(:post).
- with("environments/_default/cookbook_versions", { :run_list => ["new_run_list_recipe"] }).
- and_return({})
+ expect(http_cookbook_sync).to receive(:post)
+ .with("environments/_default/cookbook_versions", { run_list: ["new_run_list_recipe"] })
+ .and_return({})
end
before do
@@ -282,7 +293,7 @@ describe Chef::Client do
describe "when handling run failures" do
it "should remove the run_lock on failure of #load_node" do
- @run_lock = double("Chef::RunLock", :acquire => true)
+ @run_lock = double("Chef::RunLock", acquire: true)
allow(Chef::RunLock).to receive(:new).and_return(@run_lock)
@events = double("Chef::EventDispatch::Dispatcher").as_null_object
@@ -399,8 +410,8 @@ describe Chef::Client do
let(:run_context) { double("Chef::RunContext") }
let(:recipe) { double("Chef::Recipe (required recipe)") }
let(:required_recipe) do
- <<EOM
-fake_recipe_variable = "for reals"
+ <<~EOM
+ fake_recipe_variable = "for reals"
EOM
end
@@ -418,8 +429,8 @@ EOM
context "when the required_recipe has bad contents" do
let(:required_recipe) do
- <<EOM
-this is not a recipe
+ <<~EOM
+ this is not a recipe
EOM
end
it "should not raise an error" do
@@ -437,7 +448,7 @@ EOM
end
it "should log and continue on" do
- expect(Chef::Log).to receive(:debug)
+ expect(logger).to receive(:trace)
client.load_required_recipe(rest, run_context)
end
end
@@ -471,13 +482,13 @@ EOM
end
it "should not log a warning message" do
- expect(Chef::Log).not_to receive(:warn)
+ expect(logger).not_to receive(:warn)
client.do_windows_admin_check
end
context "fatal admin check is configured" do
it "should not raise an exception" do
- client.do_windows_admin_check #should not raise
+ client.do_windows_admin_check # should not raise
end
end
end
@@ -488,7 +499,7 @@ EOM
end
it "should log a warning message" do
- expect(Chef::Log).to receive(:warn)
+ expect(logger).to receive(:warn)
client.do_windows_admin_check
end
@@ -549,7 +560,6 @@ EOM
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 a674d4de33..abaea6b2dc 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") }
@@ -16,9 +16,9 @@ describe Chef::ConfigFetcher do
let(:config_content) { "# The client.rb content" }
it "reads the file from disk" do
- expect(::File).to receive(:read).
- with(config_location).
- and_return(config_content)
+ expect(::File).to receive(:read)
+ .with(config_location)
+ .and_return(config_content)
expect(fetcher.read_config).to eq(config_content)
end
@@ -42,9 +42,9 @@ describe Chef::ConfigFetcher 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(::File).to receive(:read)
+ .with(config_location)
+ .and_return(valid_json)
expect(fetcher.fetch_json).to eq({ "a" => "b" })
end
@@ -53,12 +53,12 @@ describe Chef::ConfigFetcher do
it "reports the JSON error" do
- expect(::File).to receive(:read).
- with(config_location).
- and_return(invalid_json)
+ expect(::File).to receive(:read)
+ .with(config_location)
+ .and_return(invalid_json)
- expect(Chef::Application).to receive(:fatal!).
- with(invalid_json_error_regex)
+ expect(Chef::Application).to receive(:fatal!)
+ .with(invalid_json_error_regex)
fetcher.fetch_json
end
end
@@ -78,14 +78,14 @@ describe Chef::ConfigFetcher do
describe "reading the file" do
before do
- expect(Chef::HTTP::Simple).to receive(:new).
- with(config_location).
- and_return(http)
+ expect(Chef::HTTP::Simple).to receive(:new)
+ .with(config_location)
+ .and_return(http)
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
@@ -93,18 +93,18 @@ describe Chef::ConfigFetcher do
let(:config_location) { "https://example.com/foo.json" }
it "fetches the file and parses it" do
- expect(http).to receive(:get).
- with("").and_return(valid_json)
+ expect(http).to receive(:get)
+ .with("").and_return(valid_json)
expect(fetcher.fetch_json).to eq({ "a" => "b" })
end
context "and the JSON is invalid" do
it "reports the JSON error" do
- expect(http).to receive(:get).
- with("").and_return(invalid_json)
+ expect(http).to receive(:get)
+ .with("").and_return(invalid_json)
- expect(Chef::Application).to receive(:fatal!).
- with(invalid_json_error_regex)
+ expect(Chef::Application).to receive(:fatal!)
+ .with(invalid_json_error_regex)
fetcher.fetch_json
end
end
diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb
index 68cb589251..c36f66f18a 100644
--- a/spec/unit/config_spec.rb
+++ b/spec/unit/config_spec.rb
@@ -7,8 +7,8 @@ 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).
- with(/Ohai::Config\[:#{option}\] is deprecated/)
+ expect(Chef::Log).to_not receive(:warn)
+ .with(/Ohai::Config\[:#{option}\] is deprecated/)
Chef::Config[option] = value
expect(Chef::Config[option]).to eq(value)
end
diff --git a/spec/unit/cookbook/gem_installer_spec.rb b/spec/unit/cookbook/gem_installer_spec.rb
index 91e6959331..b7c8db514a 100644
--- a/spec/unit/cookbook/gem_installer_spec.rb
+++ b/spec/unit/cookbook/gem_installer_spec.rb
@@ -22,7 +22,14 @@ describe Chef::Cookbook::GemInstaller do
:cookbook,
metadata: double(
:metadata,
- gems: [["httpclient", ">= 1.0"]]
+ gems: [["httpclient", ">= 1.0", { "git" => "https://github.com/nahi/httpclient" }]]
+ )
+ ),
+ test4: double(
+ :cookbook,
+ metadata: double(
+ :metadata,
+ gems: [["httpclient", { "path" => "./gems/httpclient" }]]
)
),
}
diff --git a/spec/unit/cookbook/manifest_v0_spec.rb b/spec/unit/cookbook/manifest_v0_spec.rb
index 0f5cfbe7a4..026b0a10bd 100644
--- a/spec/unit/cookbook/manifest_v0_spec.rb
+++ b/spec/unit/cookbook/manifest_v0_spec.rb
@@ -82,7 +82,7 @@ describe Chef::Cookbook::ManifestV0 do
it "creates an all_files key and populates it" do
result = described_class.from_hash(source_hash)
- expect(result[:all_files].map { |f| f["name"] }).to match_array %w{ recipes/default.rb attributes/default.rb README.rdoc }
+ expect(result[:all_files].map { |f| f["name"] }).to match_array %w{ recipes/default.rb attributes/default.rb root_files/README.rdoc }
end
it "deletes unwanted segment types" do
diff --git a/spec/unit/cookbook/metadata_spec.rb b/spec/unit/cookbook/metadata_spec.rb
index a91feec26d..0f85d82734 100644
--- a/spec/unit/cookbook/metadata_spec.rb
+++ b/spec/unit/cookbook/metadata_spec.rb
@@ -175,15 +175,15 @@ describe Chef::Cookbook::Metadata do
describe "meta-data attributes" do
params = {
- :maintainer => "Adam Jacob",
- :maintainer_email => "adam@opscode.com",
- :license => "Apache v2.0",
- :description => "Foobar!",
- :long_description => "Much Longer\nSeriously",
- :version => "0.6.0",
- :source_url => "http://example.com",
- :issues_url => "http://example.com/issues",
- :privacy => true,
+ maintainer: "Adam Jacob",
+ maintainer_email: "adam@opscode.com",
+ license: "Apache v2.0",
+ description: "Foobar!",
+ long_description: "Much Longer\nSeriously",
+ version: "0.6.0",
+ source_url: "http://example.com",
+ issues_url: "http://example.com/issues",
+ privacy: true,
}
params.sort_by(&:to_s).each do |field, field_value|
describe field do
@@ -212,8 +212,8 @@ describe Chef::Cookbook::Metadata do
describe "describing dependencies" do
dep_types = {
- :depends => [ :dependencies, "foo::bar", "> 0.2" ],
- :provides => [ :providing, "foo::bar", "<= 0.2" ],
+ depends: [ :dependencies, "foo::bar", "> 0.2" ],
+ provides: [ :providing, "foo::bar", "<= 0.2" ],
}
dep_types.sort_by(&:to_s).each do |dep, dep_args|
check_with = dep_args.shift
@@ -229,8 +229,8 @@ describe Chef::Cookbook::Metadata do
end
dep_types = {
- :depends => [ :dependencies, "foo::bar", ">0.2", "> 0.2" ],
- :provides => [ :providing, "foo::bar", "<=0.2", "<= 0.2" ],
+ depends: [ :dependencies, "foo::bar", ">0.2", "> 0.2" ],
+ provides: [ :providing, "foo::bar", "<=0.2", "<= 0.2" ],
}
dep_types.sort_by(&:to_s).each do |dep, dep_args|
check_with = dep_args.shift
@@ -248,8 +248,8 @@ describe Chef::Cookbook::Metadata do
describe "in the obsoleted format" do
dep_types = {
- :depends => [ "foo::bar", "> 0.2", "< 1.0" ],
- :provides => [ "foo::bar", "> 0.2", "< 1.0" ],
+ depends: [ "foo::bar", "> 0.2", "< 1.0" ],
+ provides: [ "foo::bar", "> 0.2", "< 1.0" ],
}
dep_types.each do |dep, dep_args|
@@ -261,8 +261,8 @@ describe Chef::Cookbook::Metadata do
describe "with obsolete operators" do
dep_types = {
- :depends => [ "foo::bar", ">> 0.2"],
- :provides => [ "foo::bar", ">> 0.2"],
+ depends: [ "foo::bar", ">> 0.2"],
+ provides: [ "foo::bar", ">> 0.2"],
}
dep_types.each do |dep, dep_args|
@@ -435,61 +435,61 @@ describe Chef::Cookbook::Metadata do
it "should not accept anything but a string for display_name" do
expect do
- metadata.attribute("db/mysql/databases", :display_name => "foo")
+ metadata.attribute("db/mysql/databases", display_name: "foo")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :display_name => Hash.new)
+ metadata.attribute("db/mysql/databases", display_name: Hash.new)
end.to raise_error(ArgumentError)
end
it "should not accept anything but a string for the description" do
expect do
- metadata.attribute("db/mysql/databases", :description => "foo")
+ metadata.attribute("db/mysql/databases", description: "foo")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :description => Hash.new)
+ metadata.attribute("db/mysql/databases", description: Hash.new)
end.to raise_error(ArgumentError)
end
it "should not accept anything but a string for the source_url" do
expect do
- metadata.attribute("db/mysql/databases", :source_url => "foo")
+ metadata.attribute("db/mysql/databases", source_url: "foo")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :source_url => Hash.new)
+ metadata.attribute("db/mysql/databases", source_url: Hash.new)
end.to raise_error(ArgumentError)
end
it "should not accept anything but a string for the issues_url" do
expect do
- metadata.attribute("db/mysql/databases", :issues_url => "foo")
+ metadata.attribute("db/mysql/databases", issues_url: "foo")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :issues_url => Hash.new)
+ metadata.attribute("db/mysql/databases", issues_url: Hash.new)
end.to raise_error(ArgumentError)
end
it "should not accept anything but true or false for the privacy flag" do
expect do
- metadata.attribute("db/mysql/databases", :privacy => true)
+ metadata.attribute("db/mysql/databases", privacy: true)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :privacy => false)
+ metadata.attribute("db/mysql/databases", privacy: false)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :privacy => "true")
+ metadata.attribute("db/mysql/databases", privacy: "true")
end.to raise_error(ArgumentError)
end
it "should not accept anything but an array of strings for choice" do
expect do
- metadata.attribute("db/mysql/databases", :choice => %w{dedicated shared})
+ metadata.attribute("db/mysql/databases", choice: %w{dedicated shared})
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :choice => [10, "shared"])
+ metadata.attribute("db/mysql/databases", choice: [10, "shared"])
end.to raise_error(ArgumentError)
expect do
- metadata.attribute("db/mysql/databases", :choice => Hash.new)
+ metadata.attribute("db/mysql/databases", choice: Hash.new)
end.to raise_error(ArgumentError)
end
@@ -500,13 +500,13 @@ describe Chef::Cookbook::Metadata do
it "should let calculated be true or false" do
expect do
- metadata.attribute("db/mysql/databases", :calculated => true)
+ metadata.attribute("db/mysql/databases", calculated: true)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :calculated => false)
+ metadata.attribute("db/mysql/databases", calculated: false)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :calculated => Hash.new)
+ metadata.attribute("db/mysql/databases", calculated: Hash.new)
end.to raise_error(ArgumentError)
end
@@ -517,55 +517,55 @@ describe Chef::Cookbook::Metadata do
it "accepts String for the attribute type" do
expect do
- metadata.attribute("db/mysql/databases", :type => "string")
+ metadata.attribute("db/mysql/databases", type: "string")
end.not_to raise_error
end
it "accepts Array for the attribute type" do
expect do
- metadata.attribute("db/mysql/databases", :type => "array")
+ metadata.attribute("db/mysql/databases", type: "array")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :type => Array.new)
+ metadata.attribute("db/mysql/databases", type: Array.new)
end.to raise_error(ArgumentError)
end
it "accepts symbol for the attribute type" do
expect do
- metadata.attribute("db/mysql/databases", :type => "symbol")
+ metadata.attribute("db/mysql/databases", type: "symbol")
end.not_to raise_error
end
it "should let type be hash (backwards compatibility only)" do
expect do
- metadata.attribute("db/mysql/databases", :type => "hash")
+ metadata.attribute("db/mysql/databases", type: "hash")
end.not_to raise_error
end
it "should let required be required, recommended or optional" do
expect do
- metadata.attribute("db/mysql/databases", :required => "required")
+ metadata.attribute("db/mysql/databases", required: "required")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :required => "recommended")
+ metadata.attribute("db/mysql/databases", required: "recommended")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :required => "optional")
+ metadata.attribute("db/mysql/databases", required: "optional")
end.not_to raise_error
end
it "should convert required true to required" do
expect do
- metadata.attribute("db/mysql/databases", :required => true)
+ metadata.attribute("db/mysql/databases", required: true)
end.not_to raise_error
- #attrib = metadata.attributes["db/mysql/databases"][:required].should == "required"
+ # attrib = metadata.attributes["db/mysql/databases"][:required].should == "required"
end
it "should convert required false to optional" do
expect do
- metadata.attribute("db/mysql/databases", :required => false)
+ metadata.attribute("db/mysql/databases", required: false)
end.not_to raise_error
- #attrib = metadata.attributes["db/mysql/databases"][:required].should == "optional"
+ # attrib = metadata.attributes["db/mysql/databases"][:required].should == "optional"
end
it "should set required to 'optional' by default" do
@@ -575,10 +575,10 @@ describe Chef::Cookbook::Metadata do
it "should make sure recipes is an array" do
expect do
- metadata.attribute("db/mysql/databases", :recipes => [])
+ metadata.attribute("db/mysql/databases", recipes: [])
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :required => Hash.new)
+ metadata.attribute("db/mysql/databases", required: Hash.new)
end.to raise_error(ArgumentError)
end
@@ -589,57 +589,57 @@ describe Chef::Cookbook::Metadata do
it "should allow the default value to be a string, array, hash, boolean or numeric" do
expect do
- metadata.attribute("db/mysql/databases", :default => [])
+ metadata.attribute("db/mysql/databases", default: [])
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :default => {})
+ metadata.attribute("db/mysql/databases", default: {})
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :default => "alice in chains")
+ metadata.attribute("db/mysql/databases", default: "alice in chains")
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :default => 1337)
+ metadata.attribute("db/mysql/databases", default: 1337)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :default => true)
+ metadata.attribute("db/mysql/databases", default: true)
end.not_to raise_error
expect do
- metadata.attribute("db/mysql/databases", :required => :not_gonna_do_it)
+ metadata.attribute("db/mysql/databases", required: :not_gonna_do_it)
end.to raise_error(ArgumentError)
end
it "should limit the types allowed in the choice array" do
options = {
- :type => "string",
- :choice => %w{test1 test2},
- :default => "test1",
+ type: "string",
+ choice: %w{test1 test2},
+ default: "test1",
}
expect do
metadata.attribute("test_cookbook/test", options)
end.not_to raise_error
options = {
- :type => "boolean",
- :choice => [ true, false ],
- :default => true,
+ type: "boolean",
+ choice: [ true, false ],
+ default: true,
}
expect do
metadata.attribute("test_cookbook/test", options)
end.not_to raise_error
options = {
- :type => "numeric",
- :choice => [ 1337, 420 ],
- :default => 1337,
+ type: "numeric",
+ choice: [ 1337, 420 ],
+ default: 1337,
}
expect do
metadata.attribute("test_cookbook/test", options)
end.not_to raise_error
options = {
- :type => "numeric",
- :choice => [ true, "false" ],
- :default => false,
+ type: "numeric",
+ choice: [ true, "false" ],
+ default: false,
}
expect do
metadata.attribute("test_cookbook/test", options)
@@ -649,15 +649,15 @@ describe Chef::Cookbook::Metadata do
it "should error if default used with calculated" do
expect do
attrs = {
- :calculated => true,
- :default => [ "I thought you said calculated" ],
+ calculated: true,
+ default: [ "I thought you said calculated" ],
}
metadata.attribute("db/mysql/databases", attrs)
end.to raise_error(ArgumentError)
expect do
attrs = {
- :calculated => true,
- :default => "I thought you said calculated",
+ calculated: true,
+ default: "I thought you said calculated",
}
metadata.attribute("db/mysql/databases", attrs)
end.to raise_error(ArgumentError)
@@ -666,15 +666,15 @@ describe Chef::Cookbook::Metadata do
it "should allow a default that is a choice" do
expect do
attrs = {
- :choice => %w{a b c},
- :default => "b",
+ choice: %w{a b c},
+ default: "b",
}
metadata.attribute("db/mysql/databases", attrs)
end.not_to raise_error
expect do
attrs = {
- :choice => %w{a b c d e},
- :default => %w{b d},
+ choice: %w{a b c d e},
+ default: %w{b d},
}
metadata.attribute("db/mysql/databases", attrs)
end.not_to raise_error
@@ -683,15 +683,15 @@ describe Chef::Cookbook::Metadata do
it "should error if default is not a choice" do
expect do
attrs = {
- :choice => %w{a b c},
- :default => "d",
+ choice: %w{a b c},
+ default: "d",
}
metadata.attribute("db/mysql/databases", attrs)
end.to raise_error(ArgumentError)
expect do
attrs = {
- :choice => %w{a b c d e},
- :default => %w{b z},
+ choice: %w{a b c d e},
+ default: %w{b z},
}
metadata.attribute("db/mysql/databases", attrs)
end.to raise_error(ArgumentError)
@@ -724,8 +724,8 @@ describe Chef::Cookbook::Metadata do
end
it "should automatically provide each recipe" do
- expect(metadata.providing.has_key?("test_cookbook")).to eq(true)
- expect(metadata.providing.has_key?("test_cookbook::enlighten")).to eq(true)
+ expect(metadata.providing.key?("test_cookbook")).to eq(true)
+ expect(metadata.providing.key?("test_cookbook::enlighten")).to eq(true)
end
end
@@ -743,7 +743,7 @@ describe Chef::Cookbook::Metadata do
metadata.provides "foo(:bar, :baz)"
metadata.recipe "test_cookbook::enlighten", "is your buddy"
metadata.attribute "bizspark/has_login",
- :display_name => "You have nothing"
+ display_name: "You have nothing"
metadata.version "1.2.3"
metadata.gem "foo", "~> 1.2"
metadata.gem "bar", ">= 2.2", "< 4.0"
@@ -871,7 +871,7 @@ describe Chef::Cookbook::Metadata do
describe "from_file" do
it "ignores unknown metadata fields in metadata.rb files" do
- expect(Chef::Log).to receive(:debug).with(/ignoring method some_spiffy_new_metadata_field/)
+ expect(Chef::Log).to receive(:trace).with(/ignoring method some_spiffy_new_metadata_field/)
Tempfile.open("metadata.rb") do |f|
f.write <<-EOF
some_spiffy_new_metadata_field "stuff its set to"
diff --git a/spec/unit/cookbook/synchronizer_spec.rb b/spec/unit/cookbook/synchronizer_spec.rb
index 6578a9e670..8421b1ffd1 100644
--- a/spec/unit/cookbook/synchronizer_spec.rb
+++ b/spec/unit/cookbook/synchronizer_spec.rb
@@ -116,9 +116,12 @@ describe Chef::CookbookSynchronizer do
let(:no_lazy_load) { true }
+ let(:skip_cookbook_sync) { false }
+
let(:synchronizer) do
Chef::Config[:no_lazy_load] = no_lazy_load
Chef::Config[:file_cache_path] = "/file-cache"
+ Chef::Config[:skip_cookbook_sync] = skip_cookbook_sync
Chef::CookbookSynchronizer.new(cookbook_manifest, events)
end
@@ -195,223 +198,223 @@ describe Chef::CookbookSynchronizer do
let(:cookbook_a_default_recipe_tempfile) do
double("Tempfile for cookbook_a default.rb recipe",
- :path => "/tmp/cookbook_a_recipes_default_rb")
+ path: "/tmp/cookbook_a_recipes_default_rb")
end
let(:cookbook_a_default_attribute_tempfile) do
double("Tempfile for cookbook_a default.rb attr file",
- :path => "/tmp/cookbook_a_attributes_default_rb")
+ path: "/tmp/cookbook_a_attributes_default_rb")
end
let(:cookbook_a_file_default_tempfile) do
double("Tempfile for cookbook_a megaman.conf file",
- :path => "/tmp/cookbook_a_file_default_tempfile")
+ path: "/tmp/cookbook_a_file_default_tempfile")
end
let(:cookbook_a_template_default_tempfile) do
double("Tempfile for cookbook_a apache.conf.erb template",
- :path => "/tmp/cookbook_a_template_default_tempfile")
+ path: "/tmp/cookbook_a_template_default_tempfile")
end
def setup_common_files_missing_expectations
# Files are not in the cache:
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/recipes/default.rb").
- and_return(false)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/attributes/default.rb").
- and_return(false)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/recipes/default.rb")
+ .and_return(false)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/attributes/default.rb")
+ .and_return(false)
# Fetch and copy default.rb recipe
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/abc123").
- and_return(cookbook_a_default_recipe_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/recipes/default.rb", false).
- and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/abc123")
+ .and_return(cookbook_a_default_recipe_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/recipes/default.rb", false)
+ .and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
# Fetch and copy default.rb attribute file
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/abc456").
- and_return(cookbook_a_default_attribute_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/attributes/default.rb", false).
- and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/abc456")
+ .and_return(cookbook_a_default_attribute_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/attributes/default.rb", false)
+ .and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
end
def setup_no_lazy_files_and_templates_missing_expectations
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/files/default/megaman.conf").
- and_return(false)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb").
- and_return(false)
-
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/megaman.conf").
- and_return(cookbook_a_file_default_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/files/default/megaman.conf", false).
- and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
-
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/ffffff").
- and_return(cookbook_a_template_default_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false).
- and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf")
+ .and_return(false)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ .and_return(false)
+
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/megaman.conf")
+ .and_return(cookbook_a_file_default_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf", false)
+ .and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
+
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/ffffff")
+ .and_return(cookbook_a_template_default_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false)
+ .and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
end
def setup_common_files_chksum_mismatch_expectations
# Files are in the cache:
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/recipes/default.rb").
- and_return(true)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/attributes/default.rb").
- and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/recipes/default.rb")
+ .and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/attributes/default.rb")
+ .and_return(true)
# Fetch and copy default.rb recipe
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/abc123").
- and_return(cookbook_a_default_recipe_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/recipes/default.rb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/abc123")
+ .and_return(cookbook_a_default_recipe_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_recipes_default_rb", "cookbooks/cookbook_a/recipes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/recipes/default.rb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
# Current file has fff000, want abc123
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/recipes/default.rb").
- and_return("fff000").at_least(:once)
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ .and_return("fff000").at_least(:once)
# Fetch and copy default.rb attribute file
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/abc456").
- and_return(cookbook_a_default_attribute_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/attributes/default.rb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/abc456")
+ .and_return(cookbook_a_default_attribute_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_attributes_default_rb", "cookbooks/cookbook_a/attributes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/attributes/default.rb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
# Current file has fff000, want abc456
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/attributes/default.rb").
- and_return("fff000").at_least(:once)
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ .and_return("fff000").at_least(:once)
end
def setup_no_lazy_files_and_templates_chksum_mismatch_expectations
# Files are in the cache:
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/files/default/megaman.conf").
- and_return(true)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb").
- and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf")
+ .and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ .and_return(true)
# Fetch and copy megaman.conf
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/megaman.conf").
- and_return(cookbook_a_file_default_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/files/default/megaman.conf", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/megaman.conf")
+ .and_return(cookbook_a_file_default_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_file_default_tempfile", "cookbooks/cookbook_a/files/default/megaman.conf")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
# Fetch and copy apache2.conf template
- expect(server_api).to receive(:streaming_request).
- with("http://chef.example.com/ffffff").
- and_return(cookbook_a_template_default_tempfile)
- expect(file_cache).to receive(:move_to).
- with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(server_api).to receive(:streaming_request)
+ .with("http://chef.example.com/ffffff")
+ .and_return(cookbook_a_template_default_tempfile)
+ expect(file_cache).to receive(:move_to)
+ .with("/tmp/cookbook_a_template_default_tempfile", "cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
# Current file has fff000
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/default/megaman.conf").
- and_return("fff000")
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
+ .and_return("fff000")
# Current file has fff000
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb").
- and_return("fff000")
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ .and_return("fff000")
end
def setup_common_files_present_expectations
# Files are in the cache:
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/recipes/default.rb").
- and_return(true)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/attributes/default.rb").
- and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/recipes/default.rb")
+ .and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/attributes/default.rb")
+ .and_return(true)
# Current file has abc123, want abc123
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/recipes/default.rb").
- and_return("abc123").at_least(:once)
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ .and_return("abc123").at_least(:once)
# Current file has abc456, want abc456
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/attributes/default.rb").
- and_return("abc456").at_least(:once)
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ .and_return("abc456").at_least(:once)
# :load called twice
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/recipes/default.rb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/attributes/default.rb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/recipes/default.rb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/attributes/default.rb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
end
def setup_no_lazy_files_and_templates_present_expectations
# Files are in the cache:
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/files/default/megaman.conf").
- and_return(true)
- expect(file_cache).to receive(:has_key?).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb").
- and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf")
+ .and_return(true)
+ expect(file_cache).to receive(:key?)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ .and_return(true)
# Current file has abc124, want abc124
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/default/megaman.conf").
- and_return("abc124")
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
+ .and_return("abc124")
# Current file has abc125, want abc125
- expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file).
- with("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb").
- and_return("abc125")
+ expect(Chef::CookbookVersion).to receive(:checksum_cookbook_file)
+ .with("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ .and_return("abc125")
# :load called twice
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/files/default/megaman.conf", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
- expect(file_cache).to receive(:load).
- with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false).
- twice.
- and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/default/megaman.conf")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false)
+ .twice
+ .and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
end
describe "#server_api" do
@@ -448,8 +451,8 @@ describe Chef::CookbookSynchronizer do
it "does not fetch templates or cookbook files" do
# Implicitly tested in previous test; this test is just for behavior specification.
- expect(server_api).not_to receive(:streaming_request).
- with("http://chef.example.com/ffffff")
+ expect(server_api).not_to receive(:streaming_request)
+ .with("http://chef.example.com/ffffff")
synchronizer.sync_cookbooks
end
@@ -523,5 +526,32 @@ describe Chef::CookbookSynchronizer do
end
end
end
+
+ context "when Chef::Config[:skip_cookbook_sync] is true" do
+ let(:skip_cookbook_sync) { true }
+
+ it "loads the cookbook files and warns the user that this isn't supported" do
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/recipes/default.rb", false)
+ .once
+ .and_return("/file-cache/cookbooks/cookbook_a/recipes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/attributes/default.rb", false)
+ .once
+ .and_return("/file-cache/cookbooks/cookbook_a/attributes/default.rb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/templates/default/apache2.conf.erb", false)
+ .once
+ .and_return("/file-cache/cookbooks/cookbook_a/templates/default/apache2.conf.erb")
+ expect(file_cache).to receive(:load)
+ .with("cookbooks/cookbook_a/files/default/megaman.conf", false)
+ .once
+ .and_return("/file-cache/cookbooks/cookbook_a/files/default/megaman.conf")
+ expect(Chef::Log).to receive(:warn)
+ .with("skipping cookbook synchronization! DO NOT LEAVE THIS ENABLED IN PRODUCTION!!!")
+ .once
+ synchronizer.sync_cookbooks
+ end
+ end
end
end
diff --git a/spec/unit/cookbook_loader_spec.rb b/spec/unit/cookbook_loader_spec.rb
index a5fb622da0..6553dad433 100644
--- a/spec/unit/cookbook_loader_spec.rb
+++ b/spec/unit/cookbook_loader_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -44,10 +44,10 @@ describe Chef::CookbookLoader do
cookbook_paths.delete_if { |path| File.basename(path) == "chefignore" }
cookbook_paths.each do |cookbook_path|
- expect(Chef::Cookbook::CookbookVersionLoader).to receive(:new).
- with(cookbook_path, anything).
- once.
- and_call_original
+ expect(Chef::Cookbook::CookbookVersionLoader).to receive(:new)
+ .with(cookbook_path, anything)
+ .once
+ .and_call_original
end
expect(Chef::Log).to receive(:deprecation).with(/The cookbook\(s\): openldap exist in multiple places in your cookbook_path./)
cookbook_loader.load_cookbooks
@@ -59,13 +59,18 @@ describe Chef::CookbookLoader do
cookbook_loader.load_cookbooks
end
- it "should be possible to reload all the cookbooks without triggering deprecation warnings on all of them" do
+ it "should be possible to reload all the cookbooks without triggering deprecation warnings on all of them", chef: "< 15" do
start_merged_cookbooks = cookbook_loader.merged_cookbooks
expect(Chef::Log).to receive(:deprecation).with(/The cookbook\(s\): openldap exist in multiple places in your cookbook_path./)
cookbook_loader.load_cookbooks
expect(cookbook_loader.merged_cookbooks).to eql(start_merged_cookbooks)
end
+ it "should not support multiple merged cookbooks in the cookbook path", chef: ">= 15" do
+ start_merged_cookbooks = cookbook_loader.merged_cookbooks
+ expect { cookbook_loader.load_cookbooks }.to raise_error("FIXME WITH THE CLASS YOU DECIDE TO USE HERE")
+ end
+
describe "[]" do
it "should return cookbook objects with []" do
expect(cookbook_loader[:openldap]).to be_a_kind_of(Chef::CookbookVersion)
@@ -87,7 +92,7 @@ describe Chef::CookbookLoader do
describe "each" do
it "should allow you to iterate over cookbooks with each" do
seen = Hash.new
- cookbook_loader.each do |cookbook_name, cookbook|
+ cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
expect(seen).to have_key("openldap")
@@ -96,7 +101,7 @@ describe Chef::CookbookLoader do
it "should iterate in alphabetical order" do
seen = Array.new
- cookbook_loader.each do |cookbook_name, cookbook|
+ cookbook_loader.each_key do |cookbook_name|
seen << cookbook_name
end
expect(seen).to eq %w{angrybash apache2 borken ignorken java name-mismatch openldap preseed supports-platform-constraints}
@@ -206,7 +211,7 @@ describe Chef::CookbookLoader do
it "should have loaded the correct cookbook" do
seen = Hash.new
- cookbook_loader.each do |cookbook_name, cookbook|
+ cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
expect(seen).to have_key("openldap")
@@ -234,7 +239,7 @@ describe Chef::CookbookLoader do
it "should not load the other cookbooks" do
seen = Hash.new
- cookbook_loader.each do |cookbook_name, cookbook|
+ cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
expect(seen).not_to have_key("apache2")
@@ -272,7 +277,7 @@ describe Chef::CookbookLoader do
it "should load all cookbooks" do
seen = Hash.new
- cookbook_loader.each do |cookbook_name, cookbook|
+ cookbook_loader.each_key do |cookbook_name|
seen[cookbook_name] = true
end
expect(seen).to have_key("openldap")
diff --git a/spec/unit/cookbook_manifest_spec.rb b/spec/unit/cookbook_manifest_spec.rb
index a28eaff3d3..417a067451 100644
--- a/spec/unit/cookbook_manifest_spec.rb
+++ b/spec/unit/cookbook_manifest_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2015-2016, Chef Software Inc.
+# Copyright:: Copyright 2015-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -122,6 +122,8 @@ describe Chef::CookbookManifest do
parts = relative_path.split("/")
name = if %w{templates files}.include?(parts[0]) && parts.length == 3
File.join(parts[0], parts[2])
+ elsif parts.length == 1
+ "root_files/#{parts[0]}"
else
relative_path
end
@@ -162,7 +164,7 @@ describe Chef::CookbookManifest do
cookbook_manifest_hash = cookbook_manifest.to_hash
expect(cookbook_manifest_hash.keys).to match_array(expected_hash.keys)
- cookbook_manifest_hash.each do |key, value|
+ cookbook_manifest_hash.each_key do |key|
expect(cookbook_manifest_hash[key]).to eq(expected_hash[key])
end
end
diff --git a/spec/unit/cookbook_site_streaming_uploader_spec.rb b/spec/unit/cookbook_site_streaming_uploader_spec.rb
index 0e9c277b11..87ff7abdd7 100644
--- a/spec/unit/cookbook_site_streaming_uploader_spec.rb
+++ b/spec/unit/cookbook_site_streaming_uploader_spec.rb
@@ -102,22 +102,22 @@ 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
diff --git a/spec/unit/cookbook_uploader_spec.rb b/spec/unit/cookbook_uploader_spec.rb
index 2c36c2c9c7..26e8d28454 100644
--- a/spec/unit/cookbook_uploader_spec.rb
+++ b/spec/unit/cookbook_uploader_spec.rb
@@ -85,9 +85,9 @@ describe Chef::CookbookUploader do
end
def expect_sandbox_create
- expect(http_client).to receive(:post).
- with("sandboxes", { :checksums => checksums_set }).
- and_return(sandbox_response)
+ expect(http_client).to receive(:post)
+ .with("sandboxes", { checksums: checksums_set })
+ .and_return(sandbox_response)
end
def expect_checksum_upload
@@ -100,8 +100,8 @@ describe Chef::CookbookUploader do
"accept" => "application/json",
}
- expect(http_client).to receive(:put).
- with(url_for(md5), IO.binread(file_path), upload_headers)
+ expect(http_client).to receive(:put)
+ .with(url_for(md5), IO.binread(file_path), upload_headers)
end
end
@@ -111,14 +111,14 @@ 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)
+ expect(http_client).to receive(:put)
+ .with(expected_save_url(cookbook), cookbook)
end
end
diff --git a/spec/unit/cookbook_version_file_specificity_spec.rb b/spec/unit/cookbook_version_file_specificity_spec.rb
index ba7aaa59f5..b7d5a9b288 100644
--- a/spec/unit/cookbook_version_file_specificity_spec.rb
+++ b/spec/unit/cookbook_version_file_specificity_spec.rb
@@ -27,202 +27,202 @@ describe Chef::CookbookVersion, "file specificity" do
[
# afile.rb
{
- :name => "files/afile.rb",
- :path => "files/host-examplehost.example.org/afile.rb",
- :full_path => "/cookbook-folder/files/host-examplehost.example.org/afile.rb",
- :checksum => "csum-host",
- :specificity => "host-examplehost.example.org",
+ name: "files/afile.rb",
+ path: "files/host-examplehost.example.org/afile.rb",
+ full_path: "/cookbook-folder/files/host-examplehost.example.org/afile.rb",
+ checksum: "csum-host",
+ specificity: "host-examplehost.example.org",
},
{
- :name => "files/afile.rb",
- :path => "files/ubuntu-9.10/afile.rb",
- :full_path => "/cookbook-folder/files/ubuntu-9.10/afile.rb",
- :checksum => "csum-platver-full",
- :specificity => "ubuntu-9.10",
+ name: "files/afile.rb",
+ path: "files/ubuntu-9.10/afile.rb",
+ full_path: "/cookbook-folder/files/ubuntu-9.10/afile.rb",
+ checksum: "csum-platver-full",
+ specificity: "ubuntu-9.10",
},
{
- :name => "files/afile.rb",
- :path => "files/newubuntu-9/afile.rb",
- :full_path => "/cookbook-folder/files/newubuntu-9/afile.rb",
- :checksum => "csum-platver-partial",
- :specificity => "newubuntu-9",
+ name: "files/afile.rb",
+ path: "files/newubuntu-9/afile.rb",
+ full_path: "/cookbook-folder/files/newubuntu-9/afile.rb",
+ checksum: "csum-platver-partial",
+ specificity: "newubuntu-9",
},
{
- :name => "files/afile.rb",
- :path => "files/ubuntu/afile.rb",
- :full_path => "/cookbook-folder/files/ubuntu/afile.rb",
- :checksum => "csum-plat",
- :specificity => "ubuntu",
+ name: "files/afile.rb",
+ path: "files/ubuntu/afile.rb",
+ full_path: "/cookbook-folder/files/ubuntu/afile.rb",
+ checksum: "csum-plat",
+ specificity: "ubuntu",
},
{
- :name => "files/afile.rb",
- :path => "files/default/afile.rb",
- :full_path => "/cookbook-folder/files/default/afile.rb",
- :checksum => "csum-default",
- :specificity => "default",
+ name: "files/afile.rb",
+ path: "files/default/afile.rb",
+ full_path: "/cookbook-folder/files/default/afile.rb",
+ checksum: "csum-default",
+ specificity: "default",
},
# for different/odd platform_versions
{
- :name => "files/bfile.rb",
- :path => "files/fakeos-2.0.rc.1/bfile.rb",
- :full_path => "/cookbook-folder/files/fakeos-2.0.rc.1/bfile.rb",
- :checksum => "csum2-platver-full",
- :specificity => "fakeos-2.0.rc.1",
+ name: "files/bfile.rb",
+ path: "files/fakeos-2.0.rc.1/bfile.rb",
+ full_path: "/cookbook-folder/files/fakeos-2.0.rc.1/bfile.rb",
+ checksum: "csum2-platver-full",
+ specificity: "fakeos-2.0.rc.1",
},
{
- :name => "files/bfile.rb",
- :path => "files/newfakeos-2.0.rc/bfile.rb",
- :full_path => "/cookbook-folder/files/newfakeos-2.0.rc/bfile.rb",
- :checksum => "csum2-platver-partial",
- :specificity => "newfakeos-2.0.rc",
+ name: "files/bfile.rb",
+ path: "files/newfakeos-2.0.rc/bfile.rb",
+ full_path: "/cookbook-folder/files/newfakeos-2.0.rc/bfile.rb",
+ checksum: "csum2-platver-partial",
+ specificity: "newfakeos-2.0.rc",
},
{
- :name => "files/bfile.rb",
- :path => "files/fakeos-maple tree/bfile.rb",
- :full_path => "/cookbook-folder/files/fakeos-maple tree/bfile.rb",
- :checksum => "csum3-platver-full",
- :specificity => "maple tree",
+ name: "files/bfile.rb",
+ path: "files/fakeos-maple tree/bfile.rb",
+ full_path: "/cookbook-folder/files/fakeos-maple tree/bfile.rb",
+ checksum: "csum3-platver-full",
+ specificity: "maple tree",
},
{
- :name => "files/bfile.rb",
- :path => "files/fakeos-1/bfile.rb",
- :full_path => "/cookbook-folder/files/fakeos-1/bfile.rb",
- :checksum => "csum4-platver-full",
- :specificity => "fakeos-1",
+ name: "files/bfile.rb",
+ path: "files/fakeos-1/bfile.rb",
+ full_path: "/cookbook-folder/files/fakeos-1/bfile.rb",
+ checksum: "csum4-platver-full",
+ specificity: "fakeos-1",
},
# directory adirectory
{
- :name => "files/anotherfile1.rb",
- :path => "files/host-examplehost.example.org/adirectory/anotherfile1.rb.host",
- :full_path => "/cookbook-folder/files/host-examplehost.example.org/adirectory/anotherfile1.rb.host",
- :checksum => "csum-host-1",
- :specificity => "host-examplehost.example.org",
+ name: "files/anotherfile1.rb",
+ path: "files/host-examplehost.example.org/adirectory/anotherfile1.rb.host",
+ full_path: "/cookbook-folder/files/host-examplehost.example.org/adirectory/anotherfile1.rb.host",
+ checksum: "csum-host-1",
+ specificity: "host-examplehost.example.org",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/host-examplehost.example.org/adirectory/anotherfile2.rb.host",
- :full_path => "/cookbook-folder/files/host-examplehost.example.org/adirectory/anotherfile2.rb.host",
- :checksum => "csum-host-2",
- :specificity => "host-examplehost.example.org",
+ name: "files/anotherfile2.rb",
+ path: "files/host-examplehost.example.org/adirectory/anotherfile2.rb.host",
+ full_path: "/cookbook-folder/files/host-examplehost.example.org/adirectory/anotherfile2.rb.host",
+ checksum: "csum-host-2",
+ specificity: "host-examplehost.example.org",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/ubuntu-9.10/adirectory/anotherfile1.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/ubuntu-9.10/adirectory/anotherfile1.rb.platform-full-version",
- :checksum => "csum-platver-full-1",
- :specificity => "ubuntu-9.10",
+ name: "files/anotherfile1.rb",
+ path: "files/ubuntu-9.10/adirectory/anotherfile1.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/ubuntu-9.10/adirectory/anotherfile1.rb.platform-full-version",
+ checksum: "csum-platver-full-1",
+ specificity: "ubuntu-9.10",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/ubuntu-9.10/adirectory/anotherfile2.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/ubuntu-9.10/adirectory/anotherfile2.rb.platform-full-version",
- :checksum => "csum-platver-full-2",
- :specificity => "ubuntu-9.10",
+ name: "files/anotherfile2.rb",
+ path: "files/ubuntu-9.10/adirectory/anotherfile2.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/ubuntu-9.10/adirectory/anotherfile2.rb.platform-full-version",
+ checksum: "csum-platver-full-2",
+ specificity: "ubuntu-9.10",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/newubuntu-9/adirectory/anotherfile1.rb.platform-partial-version",
- :full_path => "/cookbook-folder/files/newubuntu-9/adirectory/anotherfile1.rb.platform-partial-version",
- :checksum => "csum-platver-partial-1",
- :specificity => "newubuntu-9",
+ name: "files/anotherfile1.rb",
+ path: "files/newubuntu-9/adirectory/anotherfile1.rb.platform-partial-version",
+ full_path: "/cookbook-folder/files/newubuntu-9/adirectory/anotherfile1.rb.platform-partial-version",
+ checksum: "csum-platver-partial-1",
+ specificity: "newubuntu-9",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/newubuntu-9/adirectory/anotherfile2.rb.platform-partial-version",
- :full_path => "/cookbook-folder/files/newubuntu-9/adirectory/anotherfile2.rb.platform-partial-version",
- :checksum => "csum-platver-partial-2",
- :specificity => "nweubuntu-9",
+ name: "files/anotherfile2.rb",
+ path: "files/newubuntu-9/adirectory/anotherfile2.rb.platform-partial-version",
+ full_path: "/cookbook-folder/files/newubuntu-9/adirectory/anotherfile2.rb.platform-partial-version",
+ checksum: "csum-platver-partial-2",
+ specificity: "nweubuntu-9",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/ubuntu/adirectory/anotherfile1.rb.platform",
- :full_path => "/cookbook-folder/files/ubuntu/adirectory/anotherfile1.rb.platform",
- :checksum => "csum-plat-1",
- :specificity => "ubuntu",
+ name: "files/anotherfile1.rb",
+ path: "files/ubuntu/adirectory/anotherfile1.rb.platform",
+ full_path: "/cookbook-folder/files/ubuntu/adirectory/anotherfile1.rb.platform",
+ checksum: "csum-plat-1",
+ specificity: "ubuntu",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/ubuntu/adirectory/anotherfile2.rb.platform",
- :full_path => "/cookbook-folder/files/ubuntu/adirectory/anotherfile2.rb.platform",
- :checksum => "csum-plat-2",
- :specificity => "ubuntu",
+ name: "files/anotherfile2.rb",
+ path: "files/ubuntu/adirectory/anotherfile2.rb.platform",
+ full_path: "/cookbook-folder/files/ubuntu/adirectory/anotherfile2.rb.platform",
+ checksum: "csum-plat-2",
+ specificity: "ubuntu",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/default/adirectory/anotherfile1.rb.default",
- :full_path => "/cookbook-folder/files/default/adirectory/anotherfile1.rb.default",
- :checksum => "csum-default-1",
- :specificity => "default",
+ name: "files/anotherfile1.rb",
+ path: "files/default/adirectory/anotherfile1.rb.default",
+ full_path: "/cookbook-folder/files/default/adirectory/anotherfile1.rb.default",
+ checksum: "csum-default-1",
+ specificity: "default",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/default/adirectory/anotherfile2.rb.default",
- :full_path => "/cookbook-folder/files/default/adirectory/anotherfile2.rb.default",
- :checksum => "csum-default-2",
- :specificity => "default",
+ name: "files/anotherfile2.rb",
+ path: "files/default/adirectory/anotherfile2.rb.default",
+ full_path: "/cookbook-folder/files/default/adirectory/anotherfile2.rb.default",
+ checksum: "csum-default-2",
+ specificity: "default",
},
# for different/odd platform_versions
{
- :name => "files/anotherfile1.rb",
- :path => "files/fakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-full-version",
- :checksum => "csum2-platver-full-1",
- :specificity => "fakeos-2.0.rc.1",
+ name: "files/anotherfile1.rb",
+ path: "files/fakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-full-version",
+ checksum: "csum2-platver-full-1",
+ specificity: "fakeos-2.0.rc.1",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/fakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-full-version",
- :checksum => "csum2-platver-full-2",
- :specificity => "fakeos-2.0.rc.1",
+ name: "files/anotherfile2.rb",
+ path: "files/fakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-full-version",
+ checksum: "csum2-platver-full-2",
+ specificity: "fakeos-2.0.rc.1",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/newfakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-partial-version",
- :full_path => "/cookbook-folder/files/newfakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-partial-version",
- :checksum => "csum2-platver-partial-1",
- :specificity => "newfakeos-2.0.rc",
+ name: "files/anotherfile1.rb",
+ path: "files/newfakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-partial-version",
+ full_path: "/cookbook-folder/files/newfakeos-2.0.rc.1/adirectory/anotherfile1.rb.platform-partial-version",
+ checksum: "csum2-platver-partial-1",
+ specificity: "newfakeos-2.0.rc",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/newfakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-partial-version",
- :full_path => "/cookbook-folder/files/newfakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-partial-version",
- :checksum => "csum2-platver-partial-2",
- :specificity => "newfakeos-2.0.rc",
+ name: "files/anotherfile2.rb",
+ path: "files/newfakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-partial-version",
+ full_path: "/cookbook-folder/files/newfakeos-2.0.rc.1/adirectory/anotherfile2.rb.platform-partial-version",
+ checksum: "csum2-platver-partial-2",
+ specificity: "newfakeos-2.0.rc",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/fakeos-maple tree/adirectory/anotherfile1.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-maple tree/adirectory/anotherfile1.rb.platform-full-version",
- :checksum => "csum3-platver-full-1",
- :specificity => "fakeos-maple tree",
+ name: "files/anotherfile1.rb",
+ path: "files/fakeos-maple tree/adirectory/anotherfile1.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-maple tree/adirectory/anotherfile1.rb.platform-full-version",
+ checksum: "csum3-platver-full-1",
+ specificity: "fakeos-maple tree",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/fakeos-maple tree/adirectory/anotherfile2.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-maple tree/adirectory/anotherfile2.rb.platform-full-version",
- :checksum => "csum3-platver-full-2",
- :specificity => "fakeos-maple tree",
+ name: "files/anotherfile2.rb",
+ path: "files/fakeos-maple tree/adirectory/anotherfile2.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-maple tree/adirectory/anotherfile2.rb.platform-full-version",
+ checksum: "csum3-platver-full-2",
+ specificity: "fakeos-maple tree",
},
{
- :name => "files/anotherfile1.rb",
- :path => "files/fakeos-1/adirectory/anotherfile1.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-1/adirectory/anotherfile1.rb.platform-full-version",
- :checksum => "csum4-platver-full-1",
- :specificity => "fakeos-1",
+ name: "files/anotherfile1.rb",
+ path: "files/fakeos-1/adirectory/anotherfile1.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-1/adirectory/anotherfile1.rb.platform-full-version",
+ checksum: "csum4-platver-full-1",
+ specificity: "fakeos-1",
},
{
- :name => "files/anotherfile2.rb",
- :path => "files/fakeos-1/adirectory/anotherfile2.rb.platform-full-version",
- :full_path => "/cookbook-folder/files/fakeos-1/adirectory/anotherfile2.rb.platform-full-version",
- :checksum => "csum4-platver-full-2",
- :specificity => "fakeos-1",
+ name: "files/anotherfile2.rb",
+ path: "files/fakeos-1/adirectory/anotherfile2.rb.platform-full-version",
+ full_path: "/cookbook-folder/files/fakeos-1/adirectory/anotherfile2.rb.platform-full-version",
+ checksum: "csum4-platver-full-2",
+ specificity: "fakeos-1",
},
],
}
diff --git a/spec/unit/daemon_spec.rb b/spec/unit/daemon_spec.rb
index ae3d626113..6722fbe12c 100644
--- a/spec/unit/daemon_spec.rb
+++ b/spec/unit/daemon_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: AJ Christensen (<aj@junglist.gen.nz>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,10 +19,13 @@ require "spec_helper"
require "ostruct"
describe Chef::Daemon do
+ let(:testuser) { "thisisausernamewhichshouldnotexist" }
+ let(:testgroup) { "thisisagroupnamewhichshouldnotexist" }
+
before do
if windows?
- mock_struct = #Struct::Passwd.new(nil, nil, 111, 111)
- mock_struct = OpenStruct.new(:uid => 2342, :gid => 2342)
+ mock_struct = # Struct::Passwd.new(nil, nil, 111, 111)
+ mock_struct = OpenStruct.new(uid: 2342, gid: 2342)
allow(Etc).to receive(:getpwnam).and_return mock_struct
allow(Etc).to receive(:getgrnam).and_return mock_struct
# mock unimplemented methods
@@ -73,8 +76,9 @@ describe Chef::Daemon do
describe ".change_privilege" do
before do
+ allow(Chef::Daemon).to receive(:_change_privilege)
allow(Chef::Application).to receive(:fatal!).and_return(true)
- Chef::Config[:user] = "aj"
+ Chef::Config[:user] = testuser
allow(Dir).to receive(:chdir)
end
@@ -86,28 +90,28 @@ describe Chef::Daemon do
describe "when the user and group options are supplied" do
before do
- Chef::Config[:group] = "staff"
+ Chef::Config[:group] = testgroup
end
it "should log an appropriate info message" do
- expect(Chef::Log).to receive(:info).with("About to change privilege to aj:staff")
+ expect(Chef::Log).to receive(:info).with("About to change privilege to #{testuser}:#{testgroup}")
Chef::Daemon.change_privilege
end
it "should call _change_privilege with the user and group" do
- expect(Chef::Daemon).to receive(:_change_privilege).with("aj", "staff")
+ expect(Chef::Daemon).to receive(:_change_privilege).with(testuser, testgroup)
Chef::Daemon.change_privilege
end
end
describe "when just the user option is supplied" do
it "should log an appropriate info message" do
- expect(Chef::Log).to receive(:info).with("About to change privilege to aj")
+ expect(Chef::Log).to receive(:info).with("About to change privilege to #{testuser}")
Chef::Daemon.change_privilege
end
it "should call _change_privilege with just the user" do
- expect(Chef::Daemon).to receive(:_change_privilege).with("aj")
+ expect(Chef::Daemon).to receive(:_change_privilege).with(testuser)
Chef::Daemon.change_privilege
end
end
@@ -122,8 +126,8 @@ describe Chef::Daemon do
allow(Process::UID).to receive(:change_privilege).and_return(nil)
allow(Process::GID).to receive(:change_privilege).and_return(nil)
- @pw_user = double("Struct::Passwd", :uid => 501)
- @pw_group = double("Struct::Group", :gid => 20)
+ @pw_user = double("Struct::Passwd", uid: 501)
+ @pw_group = double("Struct::Group", gid: 20)
allow(Process).to receive(:initgroups).and_return(true)
@@ -138,18 +142,18 @@ describe Chef::Daemon do
end
it "should initialize the supplemental group list" do
- expect(Process).to receive(:initgroups).with("aj", 20)
- Chef::Daemon._change_privilege("aj")
+ expect(Process).to receive(:initgroups).with(testuser, 20)
+ Chef::Daemon._change_privilege(testuser)
end
it "should attempt to change the process GID" do
expect(Process::GID).to receive(:change_privilege).with(20).and_return(20)
- Chef::Daemon._change_privilege("aj")
+ Chef::Daemon._change_privilege(testuser)
end
it "should attempt to change the process UID" do
expect(Process::UID).to receive(:change_privilege).with(501).and_return(501)
- Chef::Daemon._change_privilege("aj")
+ Chef::Daemon._change_privilege(testuser)
end
end
@@ -159,6 +163,11 @@ describe Chef::Daemon do
allow(Process).to receive(:egid).and_return(999)
end
+ after do
+ allow(Process).to receive(:euid).and_call_original
+ allow(Process).to receive(:egid).and_call_original
+ end
+
it "should log an appropriate error message and fail miserably" do
allow(Process).to receive(:initgroups).and_raise(Errno::EPERM)
error = "Operation not permitted"
@@ -166,7 +175,7 @@ describe Chef::Daemon do
error = "Not owner"
end
expect(Chef::Application).to receive(:fatal!).with("Permission denied when trying to change 999:999 to 501:20. #{error}")
- Chef::Daemon._change_privilege("aj")
+ Chef::Daemon._change_privilege(testuser)
end
end
diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb
index 7094a7b1f7..3ebbf5c9a0 100644
--- a/spec/unit/data_bag_item_spec.rb
+++ b/spec/unit/data_bag_item_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -53,7 +53,7 @@ describe Chef::DataBagItem do
end
it "should let you set the raw_data with a hash containing symbols" do
- expect { data_bag_item.raw_data = { :id => "octahedron" } }.not_to raise_error
+ expect { data_bag_item.raw_data = { id: "octahedron" } }.not_to raise_error
end
it "should let you set the raw_data from a mash" do
@@ -297,7 +297,7 @@ describe Chef::DataBagItem do
end
it "should create if the item is not found" do
- exception = double("404 error", :code => "404")
+ exception = double("404 error", code: "404")
expect(server).to receive(:put).and_raise(Net::HTTPServerException.new("foo", exception))
expect(server).to receive(:post).with("data/books", data_bag_item)
data_bag_item.save
diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb
index cadd60936e..f20148de72 100644
--- a/spec/unit/data_bag_spec.rb
+++ b/spec/unit/data_bag_spec.rb
@@ -88,7 +88,7 @@ describe Chef::DataBag do
end
it "should silently proceed when the data bag already exists" do
- exception = double("409 error", :code => "409")
+ exception = double("409 error", code: "409")
expect(@rest).to receive(:post).and_raise(Net::HTTPServerException.new("foo", exception))
@data_bag.save
end
diff --git a/spec/unit/data_collector/messages/helpers_spec.rb b/spec/unit/data_collector/messages/helpers_spec.rb
index a241bda699..a2c6753003 100644
--- a/spec/unit/data_collector/messages/helpers_spec.rb
+++ b/spec/unit/data_collector/messages/helpers_spec.rb
@@ -124,8 +124,16 @@ describe Chef::DataCollector::Messages::Helpers do
end
describe "#node_uuid" do
+ context "when the node UUID is available in Chef::Config" do
+ it "returns the configured value" do
+ Chef::Config[:chef_guid] = "configured_uuid"
+ expect(TestMessage.node_uuid).to eq("configured_uuid")
+ end
+ end
+
context "when the node UUID can be read" do
it "returns the read-in node UUID" do
+ Chef::Config[:chef_guid] = nil
allow(TestMessage).to receive(:read_node_uuid).and_return("read_uuid")
expect(TestMessage.node_uuid).to eq("read_uuid")
end
@@ -133,6 +141,7 @@ describe Chef::DataCollector::Messages::Helpers do
context "when the node UUID cannot be read" do
it "generated a new node UUID" do
+ Chef::Config[:chef_guid] = nil
allow(TestMessage).to receive(:read_node_uuid).and_return(nil)
allow(TestMessage).to receive(:generate_node_uuid).and_return("generated_uuid")
expect(TestMessage.node_uuid).to eq("generated_uuid")
diff --git a/spec/unit/data_collector/resource_report_spec.rb b/spec/unit/data_collector/resource_report_spec.rb
index b3523622c4..1a5eab796e 100644
--- a/spec/unit/data_collector/resource_report_spec.rb
+++ b/spec/unit/data_collector/resource_report_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Salim Afiune (<afiune@chef.io)
#
-# Copyright:: Copyright 2012-2017, Chef Software Inc.
+# Copyright:: Copyright 2012-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -110,7 +110,7 @@ describe Chef::DataCollector::ResourceReport do
context "for a lazy_resource that got skipped" do
let(:resource) do
klass = Class.new(Chef::Resource) do
- resource_name "link"
+ resource_name "butters"
property :sword, String, name_property: true, identity: true
end
resource = klass.new("hyrule")
@@ -129,11 +129,11 @@ describe Chef::DataCollector::ResourceReport do
"name" => "hyrule",
"result" => "create",
"status" => "skipped",
- "type" => :link,
+ "type" => :butters,
}
end
let(:conditional) do
- double("Chef::Resource::Conditional", :to_text => "because")
+ double("Chef::Resource::Conditional", to_text: "because")
end
it "should handle any Exception and throw a helpful message by mocking the identity" do
diff --git a/spec/unit/data_collector_spec.rb b/spec/unit/data_collector_spec.rb
index f3f7ffb30f..87729d8652 100644
--- a/spec/unit/data_collector_spec.rb
+++ b/spec/unit/data_collector_spec.rb
@@ -2,7 +2,7 @@
# Author:: Adam Leff (<adamleff@chef.io)
# Author:: Ryan Cragun (<ryan@chef.io>)
#
-# Copyright:: Copyright 2012-2016, Chef Software Inc.
+# Copyright:: Copyright 2012-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,9 +25,10 @@ require "chef/resource_builder"
describe Chef::DataCollector do
describe ".register_reporter?" do
- context "when no data collector URL is configured" do
+ context "when no data collector URL or output locations are configured" do
it "returns false" do
Chef::Config[:data_collector][:server_url] = nil
+ Chef::Config[:data_collector][:output_locations] = nil
expect(Chef::DataCollector.register_reporter?).to be_falsey
end
end
@@ -134,6 +135,109 @@ describe Chef::DataCollector do
end
end
+
+ context "when output_locations are configured" do
+ before do
+ Chef::Config[:data_collector][:output_locations] = ["http://data_collector", "/tmp/data_collector.json"]
+ end
+
+ context "when operating in why_run mode" do
+ it "returns false" do
+ Chef::Config[:why_run] = true
+ expect(Chef::DataCollector.register_reporter?).to be_falsey
+ end
+ end
+
+ context "when not operating in why_run mode" do
+
+ before do
+ Chef::Config[:why_run] = false
+ Chef::Config[:data_collector][:token] = token
+ end
+
+ context "when a token is configured" do
+
+ let(:token) { "supersecrettoken" }
+
+ context "when report is enabled for current mode" do
+ it "returns true" do
+ allow(Chef::DataCollector).to receive(:reporter_enabled_for_current_mode?).and_return(true)
+ expect(Chef::DataCollector.register_reporter?).to be_truthy
+ end
+ end
+
+ context "when report is disabled for current mode" do
+ it "returns false" do
+ allow(Chef::DataCollector).to receive(:reporter_enabled_for_current_mode?).and_return(false)
+ expect(Chef::DataCollector.register_reporter?).to be_falsey
+ end
+ end
+
+ end
+
+ # `Chef::Config[:data_collector][:server_url]` defaults to a URL
+ # relative to the `chef_server_url`, so we use configuration of the
+ # token to infer whether a solo/local mode user intends for data
+ # collection to be enabled.
+ context "when a token is not configured" do
+
+ let(:token) { nil }
+
+ context "when report is enabled for current mode" do
+
+ before do
+ allow(Chef::DataCollector).to receive(:reporter_enabled_for_current_mode?).and_return(true)
+ end
+
+ context "when the current mode is solo" do
+
+ before do
+ Chef::Config[:solo] = true
+ end
+
+ it "returns true" do
+ expect(Chef::DataCollector.register_reporter?).to be(true)
+ end
+
+ end
+
+ context "when the current mode is local mode" do
+
+ before do
+ Chef::Config[:local_mode] = true
+ end
+
+ it "returns false" do
+ expect(Chef::DataCollector.register_reporter?).to be(true)
+ end
+ end
+
+ context "when the current mode is client mode" do
+
+ before do
+ Chef::Config[:local_mode] = false
+ Chef::Config[:solo] = false
+ end
+
+ it "returns true" do
+ expect(Chef::DataCollector.register_reporter?).to be_truthy
+ end
+
+ end
+
+ end
+
+ context "when report is disabled for current mode" do
+ it "returns false" do
+ allow(Chef::DataCollector).to receive(:reporter_enabled_for_current_mode?).and_return(false)
+ expect(Chef::DataCollector.register_reporter?).to be_falsey
+ end
+ end
+
+ end
+
+ end
+ end
end
describe ".reporter_enabled_for_current_mode?" do
@@ -656,6 +760,13 @@ describe Chef::DataCollector::Reporter do
end
end
+ context "when server_url is omitted but output_locations is specified" do
+ it "does not an exception" do
+ Chef::Config[:data_collector][:output_locations] = ["http://data_collector", "/tmp/data_collector.json"]
+ expect { reporter.send(:validate_data_collector_server_url!) }.not_to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+
context "when server_url is not empty" do
context "when server_url is an invalid URI" do
it "raises an exception" do
@@ -683,6 +794,30 @@ describe Chef::DataCollector::Reporter do
end
end
+ describe "#validate_data_collector_output_locations!" do
+ context "when output_locations is empty" do
+ it "raises an exception" do
+ Chef::Config[:data_collector][:output_locations] = {}
+ expect { reporter.send(:validate_data_collector_output_locations!) }.to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+
+ context "when valid output_locations are provided" do
+ it "does not raise an exception" do
+ expect(reporter).to receive(:open).with("data_collection.json", "a")
+ Chef::Config[:data_collector][:output_locations] = { urls: ["http://data_collector"], files: ["data_collection.json"] }
+ expect { reporter.send(:validate_data_collector_output_locations!) }.not_to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+
+ context "when output_locations contains an invalid URI" do
+ it "raises an exception" do
+ Chef::Config[:data_collector][:output_locations] = { urls: ["this is not a url"], files: ["/tmp/data_collection.json"] }
+ expect { reporter.send(:validate_data_collector_output_locations!) }.to raise_error(Chef::Exceptions::ConfigurationError)
+ end
+ end
+ end
+
describe "#detect_unprocessed_resources" do
context "when resources do not override core methods" do
it "adds resource reports for any resources that have not yet been processed" do
diff --git a/spec/unit/deprecated_spec.rb b/spec/unit/deprecated_spec.rb
index 9be792ab20..9c60080cef 100644
--- a/spec/unit/deprecated_spec.rb
+++ b/spec/unit/deprecated_spec.rb
@@ -1,5 +1,5 @@
#
-# Copyright:: Copyright 2013-2016, Chef Software Inc.
+# Copyright:: Copyright 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,40 +20,46 @@ require "chef/deprecated"
describe Chef::Deprecated do
class TestDeprecation < Chef::Deprecated::Base
- def id; 999; end
-
- def target; "test.html"; end
-
- def link; "#{Chef::Deprecated::Base::BASE_URL}test.html"; end
+ target 999, "test.html"
end
context "loading a deprecation class" do
it "loads the correct class" do
- expect(Chef::Deprecated.create(:test_deprecation)).to be_an_instance_of(Chef::Deprecated::TestDeprecation)
+ expect(Chef::Deprecated.create(:test_deprecation, nil, nil)).to be_an_instance_of(TestDeprecation)
end
- it "optionally sets a message" do
- deprecation = Chef::Deprecated.create(:test_deprecation, "A test message")
+ it "sets a message" do
+ deprecation = Chef::Deprecated.create(:test_deprecation, "A test message", nil)
expect(deprecation.message).to eql("A test message")
end
- it "optionally sets the location" do
+ it "sets the location" do
deprecation = Chef::Deprecated.create(:test_deprecation, nil, "A test location")
expect(deprecation.location).to eql("A test location")
end
end
context "formatting deprecation warnings" do
- let(:base_url) { Chef::Deprecated::Base::BASE_URL }
let(:message) { "A test message" }
let(:location) { "the location" }
it "displays the full URL" do
- expect(Chef::Deprecated::TestDeprecation.new().url).to eql("#{base_url}test.html")
+ expect(TestDeprecation.new().url).to eql("https://docs.chef.io/deprecations_test.html")
end
it "formats a complete deprecation message" do
- expect(Chef::Deprecated::TestDeprecation.new(message, location).inspect).to eql("#{message} (CHEF-999)#{location}.\nhttps://docs.chef.io/deprecations_test.html")
+ expect(TestDeprecation.new(message, location).to_s).to eql("Deprecation CHEF-999 from the location\n\n A test message\n\nPlease see https://docs.chef.io/deprecations_test.html for further details and information on how to correct this problem.")
+ end
+ end
+
+ it "has no overlapping deprecation IDs" do
+ id_map = {}
+ ObjectSpace.each_object(Class).select { |cls| cls < Chef::Deprecated::Base }.each do |cls|
+ (id_map[cls.deprecation_id] ||= []) << cls
+ end
+ collisions = id_map.select { |k, v| v.size != 1 }
+ unless collisions.empty?
+ raise "Found deprecation ID collisions:\n#{collisions.map { |k, v| "* #{k} #{v.map(&:name).join(', ')}" }.join("\n")}"
end
end
end
diff --git a/spec/unit/dsl/audit_spec.rb b/spec/unit/dsl/audit_spec.rb
index 42e543fdb2..e24fbc4589 100644
--- a/spec/unit/dsl/audit_spec.rb
+++ b/spec/unit/dsl/audit_spec.rb
@@ -12,7 +12,7 @@ end
describe Chef::DSL::Audit do
let(:auditor) { AuditDSLTester.new("cookbook_name", "recipe_name", run_context) }
- let(:run_context) { instance_double(Chef::RunContext, :audits => audits, :cookbook_collection => cookbook_collection) }
+ let(:run_context) { instance_double(Chef::RunContext, audits: audits, cookbook_collection: cookbook_collection) }
let(:audits) { {} }
let(:cookbook_collection) { {} }
diff --git a/spec/unit/dsl/declare_resource_spec.rb b/spec/unit/dsl/declare_resource_spec.rb
index 57a7fd7f18..255e85e22e 100644
--- a/spec/unit/dsl/declare_resource_spec.rb
+++ b/spec/unit/dsl/declare_resource_spec.rb
@@ -1,5 +1,5 @@
#
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,6 +32,15 @@ describe Chef::ResourceCollection do
Chef::Recipe.new("hjk", "test", run_context)
end
+ describe "mixed in correctly" do
+ it "the resources() method winds up in the right classes" do
+ methods = [ :resources, :find_resource, :find_resource!, :edit_resource, :edit_resource!, :delete_resource, :delete_resource!, :declare_resource, :build_resource ]
+ expect(Chef::Resource.instance_methods).to include(*methods)
+ expect(Chef::Recipe.instance_methods).to include(*methods)
+ expect(Chef::Provider.instance_methods).to include(*methods)
+ end
+ end
+
describe "#declare_resource" do
before do
recipe.declare_resource(:zen_master, "monkey") do
diff --git a/spec/unit/dsl/platform_introspection_spec.rb b/spec/unit/dsl/platform_introspection_spec.rb
index fd1f9b23b5..51123ba930 100644
--- a/spec/unit/dsl/platform_introspection_spec.rb
+++ b/spec/unit/dsl/platform_introspection_spec.rb
@@ -39,8 +39,8 @@ end
describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do
before do
platform_hash = {
- :openbsd => { :default => "free, functional, secure" },
- [:redhat, :centos, :fedora, :scientific] => { :default => '"stable"' },
+ :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",
}
@@ -48,24 +48,24 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do
end
it "returns the default value when the platform doesn't match" do
- expect(@platform_specific_value.value_for_node(:platform => :dos)).to eq("bork da bork")
+ expect(@platform_specific_value.value_for_node(platform: :dos)).to eq("bork da bork")
end
it "returns a value for a platform set as a group" do
- expect(@platform_specific_value.value_for_node(:platform => :centos)).to eq('"stable"')
+ expect(@platform_specific_value.value_for_node(platform: :centos)).to eq('"stable"')
end
it "returns a value for the platform when it was set as a symbol but fetched as a string" do
- expect(@platform_specific_value.value_for_node(:platform => "centos")).to eq('"stable"')
+ expect(@platform_specific_value.value_for_node(platform: "centos")).to eq('"stable"')
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
@@ -73,11 +73,11 @@ describe Chef::DSL::PlatformIntrospection::PlatformDependentValue do
# this matches the behavior in the original implementation.
# whether or not it's correct is another matter.
platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformDependentValue.new({})
- expect(platform_specific_value.value_for_node(:platform => "foo")).to be_nil
+ expect(platform_specific_value.value_for_node(platform: "foo")).to be_nil
end
it "raises an argument error if the platform hash is not correctly structured" do
- bad_hash = { :ubuntu => :foo } # should be :ubuntu => {:default => 'foo'}
+ bad_hash = { ubuntu: :foo } # should be :ubuntu => {:default => 'foo'}
expect { Chef::DSL::PlatformIntrospection::PlatformDependentValue.new(bad_hash) }.to raise_error(ArgumentError)
end
@@ -98,32 +98,32 @@ describe Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue do
end
it "returns the default value when the platform family doesn't match" do
- expect(@platform_family_value.value_for_node(:platform_family => :os2)).to eq("default value")
+ 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")
+ expect(@platform_family_value.value_for_node(platform_family: :debian)).to eq("debian value")
end
it "returns a value for the platform family when it was set as a symbol but fetched as a string" do
- expect(@platform_family_value.value_for_node(:platform_family => "gentoo")).to eq("gentoo value")
+ expect(@platform_family_value.value_for_node(platform_family: "gentoo")).to eq("gentoo value")
end
it "returns an array value stored for a platform family" do
- expect(@platform_family_value.value_for_node(:platform_family => "suse")).to eq(@array_values)
+ expect(@platform_family_value.value_for_node(platform_family: "suse")).to eq(@array_values)
end
it "returns a value for the platform family when it was set within an array hash key as a symbol" do
- expect(@platform_family_value.value_for_node(:platform_family => :rhel)).to eq("redhatty value")
+ expect(@platform_family_value.value_for_node(platform_family: :rhel)).to eq("redhatty value")
end
it "returns a value for the platform family when it was set within an array hash key as a string" do
- expect(@platform_family_value.value_for_node(:platform_family => "fedora")).to eq("redhatty value")
+ expect(@platform_family_value.value_for_node(platform_family: "fedora")).to eq("redhatty value")
end
it "returns nil if there is no default and no platforms match" do
platform_specific_value = Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue.new({})
- expect(platform_specific_value.value_for_node(:platform_family => "foo")).to be_nil
+ 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 5cd7c7794f..4f9e0b764b 100644
--- a/spec/unit/dsl/reboot_pending_spec.rb
+++ b/spec/unit/dsl/reboot_pending_spec.rb
@@ -36,7 +36,7 @@ describe Chef::DSL::RebootPending do
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)
+ 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
@@ -49,19 +49,6 @@ describe Chef::DSL::RebootPending 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)
- end
-
- 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 }])
- expect(recipe.reboot_pending?).to be_truthy
- end
- end
end
context "platform is ubuntu" do
diff --git a/spec/unit/dsl/recipe_spec.rb b/spec/unit/dsl/recipe_spec.rb
index bc97ecc029..5995abe374 100644
--- a/spec/unit/dsl/recipe_spec.rb
+++ b/spec/unit/dsl/recipe_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,11 +24,6 @@ class RecipeDSLExampleClass
include Chef::DSL::Recipe
end
-FullRecipeDSLExampleClass = Struct.new(:cookbook_name, :recipe_name)
-class FullRecipeDSLExampleClass
- include Chef::DSL::Recipe::FullDSL
-end
-
RecipeDSLBaseAPI = Struct.new(:cookbook_name, :recipe_name)
class RecipeDSLExampleSubclass < RecipeDSLBaseAPI
include Chef::DSL::Recipe
@@ -41,14 +36,6 @@ describe Chef::DSL::Recipe do
let(:cookbook_name) { "example_cb" }
let(:recipe_name) { "example_recipe" }
- it "tracks when it is included via FullDSL" do
- expect(Chef::DSL::Recipe::FullDSL.descendants).to include(FullRecipeDSLExampleClass)
- end
-
- it "doesn't track what is included via only the recipe DSL" do
- expect(Chef::DSL::Recipe::FullDSL.descendants).not_to include(RecipeDSLExampleClass)
- end
-
shared_examples_for "A Recipe DSL Implementation" do
it "responds to cookbook_name" do
@@ -66,10 +53,6 @@ describe Chef::DSL::Recipe do
it "responds to shell_out" do
expect(recipe.respond_to?(:shell_out!)).to be true
end
-
- it "responds to shell_out" do
- expect(recipe.respond_to?(:shell_out_with_systems_locale)).to be true
- end
end
context "when included in a class that defines the required interface directly" do
diff --git a/spec/unit/environment_spec.rb b/spec/unit/environment_spec.rb
index 3daae16749..a342d6d7cd 100644
--- a/spec/unit/environment_spec.rb
+++ b/spec/unit/environment_spec.rb
@@ -3,7 +3,7 @@
# Author:: Seth Falcon (<seth@ospcode.com>)
# Author:: John Keiser (<jkeiser@ospcode.com>)
# Author:: Kyle Goodwin (<kgoodwin@primerevenue.com>)
-# Copyright:: Copyright 2010-2016, Chef Software Inc.
+# Copyright:: Copyright 2010-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -73,12 +73,12 @@ describe Chef::Environment do
describe "default attributes" do
it "should let you set the attributes hash explicitly" do
- expect(@environment.default_attributes({ :one => "two" })).to eq({ :one => "two" })
+ expect(@environment.default_attributes({ one: "two" })).to eq({ one: "two" })
end
it "should let you return the attributes hash" do
- @environment.default_attributes({ :one => "two" })
- expect(@environment.default_attributes).to eq({ :one => "two" })
+ @environment.default_attributes({ one: "two" })
+ expect(@environment.default_attributes).to eq({ one: "two" })
end
it "should throw an ArgumentError if we aren't a kind of hash" do
@@ -88,12 +88,12 @@ describe Chef::Environment do
describe "override attributes" do
it "should let you set the attributes hash explicitly" do
- expect(@environment.override_attributes({ :one => "two" })).to eq({ :one => "two" })
+ expect(@environment.override_attributes({ one: "two" })).to eq({ one: "two" })
end
it "should let you return the attributes hash" do
- @environment.override_attributes({ :one => "two" })
- expect(@environment.override_attributes).to eq({ :one => "two" })
+ @environment.override_attributes({ one: "two" })
+ expect(@environment.override_attributes).to eq({ one: "two" })
end
it "should throw an ArgumentError if we aren't a kind of hash" do
@@ -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
@@ -250,7 +250,7 @@ describe Chef::Environment do
end
it "should validate the version string of each cookbook" do
- @cookbook_versions.each do |cookbook, version|
+ @cookbook_versions.each_value do |version|
expect(Chef::Environment).to receive(:validate_cookbook_version).with(version).and_return true
end
Chef::Environment.validate_cookbook_versions(@cookbook_versions)
@@ -311,17 +311,17 @@ describe Chef::Environment do
end
it "updates the name from parameters[:name]" do
- @environment.update_from_params(:name => "kurrupt")
+ @environment.update_from_params(name: "kurrupt")
expect(@environment.name).to eq("kurrupt")
end
it "validates the name given in the params" do
- expect(@environment.update_from_params(:name => "@$%^&*()")).to be_falsey
+ expect(@environment.update_from_params(name: "@$%^&*()")).to be_falsey
expect(@environment.invalid_fields[:name]).to eq(%q{Option name's value @$%^&*() does not match regular expression /^[\-[:alnum:]_]+$/})
end
it "updates the description from parameters[:description]" do
- @environment.update_from_params(:description => "wow, writing your own object mapper is kinda painful")
+ @environment.update_from_params(description: "wow, writing your own object mapper is kinda painful")
expect(@environment.description).to eq("wow, writing your own object mapper is kinda painful")
end
@@ -329,13 +329,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" })
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")
@@ -352,12 +352,12 @@ describe Chef::Environment do
end
it "updates default attributes from a JSON string in params[:attributes]" do
- @environment.update_from_params(:name => "fuuu", :default_attributes => %q|{"fuuu":"RAGE"}|)
+ @environment.update_from_params(name: "fuuu", default_attributes: %q|{"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"}|)
+ @environment.update_from_params(name: "fuuu", override_attributes: %q|{"foo":"override"}|)
expect(@environment.override_attributes).to eq({ "foo" => "override" })
end
@@ -374,7 +374,7 @@ describe Chef::Environment do
describe "list" do
describe "inflated" do
it "should return a hash of environment names and objects" do
- e1 = double("Chef::Environment", :name => "one")
+ e1 = double("Chef::Environment", name: "one")
expect(@query).to receive(:search).with(:environment).and_yield(e1)
r = Chef::Environment.list(true)
expect(r["one"]).to eq(e1)
diff --git a/spec/unit/exceptions_spec.rb b/spec/unit/exceptions_spec.rb
index e952a5448a..c892b24f28 100644
--- a/spec/unit/exceptions_spec.rb
+++ b/spec/unit/exceptions_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Exceptions do
exception_to_super_class = {
Chef::Exceptions::Application => RuntimeError,
Chef::Exceptions::Cron => RuntimeError,
- Chef::Exceptions::Env => RuntimeError,
+ Chef::Exceptions::WindowsEnv => RuntimeError,
Chef::Exceptions::Exec => RuntimeError,
Chef::Exceptions::FileNotFound => RuntimeError,
Chef::Exceptions::Package => RuntimeError,
diff --git a/spec/unit/file_access_control_spec.rb b/spec/unit/file_access_control_spec.rb
index ee806b5c3a..b9ef45dd5c 100644
--- a/spec/unit/file_access_control_spec.rb
+++ b/spec/unit/file_access_control_spec.rb
@@ -36,7 +36,7 @@ describe Chef::FileAccessControl do
@run_context = Chef::RunContext.new(@node, {}, @events)
@current_resource = Chef::Resource::File.new("/tmp/different_file.txt")
@provider_requirements = Chef::Provider::ResourceRequirements.new(@resource, @run_context)
- @provider = double("File provider", :requirements => @provider_requirements, :manage_symlink_access? => false)
+ @provider = double("File provider", requirements: @provider_requirements, manage_symlink_access?: false)
@fac = Chef::FileAccessControl.new(@current_resource, @resource, @provider)
end
@@ -61,7 +61,7 @@ describe Chef::FileAccessControl do
end
it "determines the uid of the owner specified by the resource" do
- expect(Etc).to receive(:getpwnam).with("toor").and_return(OpenStruct.new(:uid => 2342))
+ expect(Etc).to receive(:getpwnam).with("toor").and_return(OpenStruct.new(uid: 2342))
expect(@fac.target_uid).to eq(2342)
end
@@ -99,7 +99,7 @@ describe Chef::FileAccessControl do
# uids. So we have to get ruby and negative uids to smoke the peace pipe
# with each other.
@resource.owner("nobody")
- expect(Etc).to receive(:getpwnam).with("nobody").and_return(OpenStruct.new(:uid => (4294967294)))
+ expect(Etc).to receive(:getpwnam).with("nobody").and_return(OpenStruct.new(uid: (4294967294)))
expect(@fac.target_uid).to eq(-2)
end
@@ -107,7 +107,7 @@ describe Chef::FileAccessControl do
# More: when OSX userIDs are created by ActiveDirectory sync, it tends to use huge numbers
# which had been incorrectly wrapped. It does not look like the OSX IDs go below -2
@resource.owner("bigdude")
- expect(Etc).to receive(:getpwnam).with("bigdude").and_return(OpenStruct.new(:uid => (4294967286)))
+ expect(Etc).to receive(:getpwnam).with("bigdude").and_return(OpenStruct.new(uid: (4294967286)))
expect(@fac.target_uid).to eq(4294967286)
end
@@ -153,7 +153,7 @@ describe Chef::FileAccessControl do
end
it "determines the gid of the group specified by the resource" do
- expect(Etc).to receive(:getgrnam).with("wheel").and_return(OpenStruct.new(:gid => 2342))
+ expect(Etc).to receive(:getgrnam).with("wheel").and_return(OpenStruct.new(gid: 2342))
expect(@fac.target_gid).to eq(2342)
end
@@ -273,7 +273,7 @@ describe Chef::FileAccessControl do
it "sets the file's mode as specified in the resource when the current modes are incorrect" do
# stat returns modes like 0100644 (octal) => 33188 (decimal)
- #@fac.stub(:stat).and_return(OpenStruct.new(:mode => 33188))
+ # @fac.stub(:stat).and_return(OpenStruct.new(:mode => 33188))
@current_resource.mode("0644")
expect(File).to receive(:chmod).with(256, "/tmp/different_file.txt")
@fac.set_mode
@@ -286,7 +286,7 @@ describe Chef::FileAccessControl do
end
it "does not set the file's mode when the current modes are correct" do
- #@fac.stub(:stat).and_return(OpenStruct.new(:mode => 0100400))
+ # @fac.stub(:stat).and_return(OpenStruct.new(:mode => 0100400))
@current_resource.mode("0400")
expect(File).not_to receive(:chmod)
@fac.set_mode
@@ -294,7 +294,7 @@ describe Chef::FileAccessControl do
end
it "sets all access controls on a file" do
- allow(@fac).to receive(:stat).and_return(OpenStruct.new(:owner => 99, :group => 99, :mode => 0100444))
+ allow(@fac).to receive(:stat).and_return(OpenStruct.new(owner: 99, group: 99, mode: 0100444))
@resource.mode(0400)
@resource.owner(0)
@resource.group(0)
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 569fd898a7..6c8736ae38 100644
--- a/spec/unit/file_content_management/deploy/mv_unix_spec.rb
+++ b/spec/unit/file_content_management/deploy/mv_unix_spec.rb
@@ -38,9 +38,9 @@ describe Chef::FileContentManagement::Deploy::MvUnix do
let(:target_file_mode) { 0644 }
let(:target_file_stat) do
double "File::Stat struct for target file",
- :mode => target_file_mode,
- :uid => target_file_uid,
- :gid => target_file_gid
+ mode: target_file_mode,
+ uid: target_file_uid,
+ gid: target_file_gid
end
before do
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 30a62c4da9..80155f131c 100644
--- a/spec/unit/file_content_management/deploy/mv_windows_spec.rb
+++ b/spec/unit/file_content_management/deploy/mv_windows_spec.rb
@@ -59,10 +59,10 @@ describe Chef::FileContentManagement::Deploy::MvWindows do
end
before do
- allow(Chef::ReservedNames::Win32::Security::SecurableObject).
- to receive(:new).
- with(target_file_path).
- and_return(target_file_security_object, updated_target_security_object)
+ allow(Chef::ReservedNames::Win32::Security::SecurableObject)
+ .to receive(:new)
+ .with(target_file_path)
+ .and_return(target_file_security_object, updated_target_security_object)
end
@@ -84,8 +84,8 @@ describe Chef::FileContentManagement::Deploy::MvWindows do
let(:target_file_security_descriptor) do
double "security descriptor for target file",
- :group => original_target_file_group,
- :owner => original_target_file_owner
+ group: original_target_file_group,
+ owner: original_target_file_owner
end
let(:updated_target_security_descriptor) do
@@ -147,19 +147,19 @@ describe Chef::FileContentManagement::Deploy::MvWindows do
allow(target_file_security_descriptor).to receive(:dacl_inherits?).and_return(false)
allow(target_file_security_descriptor).to receive(:dacl).and_return(original_target_file_dacl)
- expect(Chef::ReservedNames::Win32::Security::ACL).
- to receive(:create).
- with([]).
- and_return(empty_dacl)
+ expect(Chef::ReservedNames::Win32::Security::ACL)
+ .to receive(:create)
+ .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)
allow(target_file_security_descriptor).to receive(:sacl).and_return(original_target_file_sacl)
- expect(Chef::ReservedNames::Win32::Security::ACL).
- to receive(:create).
- with([]).
- and_return(empty_sacl)
+ expect(Chef::ReservedNames::Win32::Security::ACL)
+ .to receive(:create)
+ .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)
@@ -171,13 +171,13 @@ describe Chef::FileContentManagement::Deploy::MvWindows do
end
context "and the target has a dacl and sacl" do
- let(:inherited_dacl_ace) { double("Windows dacl ace (inherited)", :inherited? => true) }
- let(:not_inherited_dacl_ace) { double("Windows dacl ace (not inherited)", :inherited? => false) }
+ let(:inherited_dacl_ace) { double("Windows dacl ace (inherited)", inherited?: true) }
+ let(:not_inherited_dacl_ace) { double("Windows dacl ace (not inherited)", inherited?: false) }
let(:original_target_file_dacl) { [inherited_dacl_ace, not_inherited_dacl_ace] }
- let(:inherited_sacl_ace) { double("Windows sacl ace (inherited)", :inherited? => true) }
- let(:not_inherited_sacl_ace) { double("Windows sacl ace (not inherited)", :inherited? => false) }
+ let(:inherited_sacl_ace) { double("Windows sacl ace (inherited)", inherited?: true) }
+ let(:not_inherited_sacl_ace) { double("Windows sacl ace (not inherited)", inherited?: false) }
let(:original_target_file_sacl) { [inherited_sacl_ace, not_inherited_sacl_ace] }
let(:custom_dacl) { double("Windows ACL for non-inherited dacl aces") }
@@ -188,19 +188,19 @@ describe Chef::FileContentManagement::Deploy::MvWindows do
allow(target_file_security_descriptor).to receive(:dacl_inherits?).and_return(dacl_inherits?)
allow(target_file_security_descriptor).to receive(:dacl).and_return(original_target_file_dacl)
- expect(Chef::ReservedNames::Win32::Security::ACL).
- to receive(:create).
- with([not_inherited_dacl_ace]).
- and_return(custom_dacl)
+ expect(Chef::ReservedNames::Win32::Security::ACL)
+ .to receive(:create)
+ .with([not_inherited_dacl_ace])
+ .and_return(custom_dacl)
allow(target_file_security_descriptor).to receive(:sacl_present?).and_return(true)
allow(target_file_security_descriptor).to receive(:sacl_inherits?).and_return(sacl_inherits?)
allow(target_file_security_descriptor).to receive(:sacl).and_return(original_target_file_sacl)
- expect(Chef::ReservedNames::Win32::Security::ACL).
- to receive(:create).
- with([not_inherited_sacl_ace]).
- and_return(custom_sacl)
+ expect(Chef::ReservedNames::Win32::Security::ACL)
+ .to receive(:create)
+ .with([not_inherited_sacl_ace])
+ .and_return(custom_sacl)
expect(updated_target_security_object).to receive(:set_dacl).with(custom_dacl, dacl_inherits?)
expect(updated_target_security_object).to receive(:set_sacl).with(custom_sacl, sacl_inherits?)
diff --git a/spec/unit/formatters/base_spec.rb b/spec/unit/formatters/base_spec.rb
index 30c7757e5a..19182554f9 100644
--- a/spec/unit/formatters/base_spec.rb
+++ b/spec/unit/formatters/base_spec.rb
@@ -23,6 +23,14 @@ describe Chef::Formatters::Base do
let(:out) { StringIO.new }
let(:err) { StringIO.new }
let(:formatter) { Chef::Formatters::Base.new(out, err) }
+ let(:exception) do
+ # An exception with a real backtrace.
+ begin
+ raise EOFError
+ rescue EOFError => exc
+ end
+ exc
+ end
it "starts with an indentation of zero" do
expect(formatter.output.indent).to eql(0)
@@ -45,27 +53,48 @@ describe Chef::Formatters::Base do
end
it "humanizes EOFError exceptions for #registration_failed" do
- formatter.registration_failed("foo.example.com", EOFError.new, double("Chef::Config"))
+ formatter.registration_failed("foo.example.com", exception, double("Chef::Config"))
expect(out.string).to match(/Received an EOF on transport socket/)
end
it "humanizes EOFError exceptions for #node_load_failed" do
- formatter.node_load_failed("foo.example.com", EOFError.new, double("Chef::Config"))
+ formatter.node_load_failed("foo.example.com", exception, double("Chef::Config"))
expect(out.string).to match(/Received an EOF on transport socket/)
end
it "humanizes EOFError exceptions for #run_list_expand_failed" do
- formatter.run_list_expand_failed(double("Chef::Node"), EOFError.new)
+ formatter.run_list_expand_failed(double("Chef::Node"), exception)
expect(out.string).to match(/Received an EOF on transport socket/)
end
it "humanizes EOFError exceptions for #cookbook_resolution_failed" do
- formatter.run_list_expand_failed(double("Expanded Run List"), EOFError.new)
+ formatter.run_list_expand_failed(double("Expanded Run List"), exception)
expect(out.string).to match(/Received an EOF on transport socket/)
end
it "humanizes EOFError exceptions for #cookbook_sync_failed" do
- formatter.cookbook_sync_failed("foo.example.com", EOFError.new)
+ formatter.cookbook_sync_failed("foo.example.com", exception)
expect(out.string).to match(/Received an EOF on transport socket/)
end
+
+ it "outputs error information for failed resources with ignore_failure true" do
+ resource = Chef::Resource::RubyBlock.new("test")
+ resource.ignore_failure(true)
+ formatter.resource_failed(resource, :run, exception)
+ expect(out.string).to match(/Error executing action `run` on resource 'ruby_block\[test\]'/)
+ end
+
+ it "does not output error information for failed resources with ignore_failure :quiet" do
+ resource = Chef::Resource::RubyBlock.new("test")
+ resource.ignore_failure(:quiet)
+ formatter.resource_failed(resource, :run, exception)
+ expect(out.string).to eq("")
+ end
+
+ it "does not output error information for failed resources with ignore_failure 'quiet'" do
+ resource = Chef::Resource::RubyBlock.new("test")
+ resource.ignore_failure("quiet")
+ formatter.resource_failed(resource, :run, exception)
+ expect(out.string).to eq("")
+ end
end
diff --git a/spec/unit/formatters/error_description_spec.rb b/spec/unit/formatters/error_description_spec.rb
index cf6372ed49..772ad84481 100644
--- a/spec/unit/formatters/error_description_spec.rb
+++ b/spec/unit/formatters/error_description_spec.rb
@@ -69,17 +69,17 @@ describe Chef::Formatters::ErrorDescription do
context "when no sections have been added" do
it "should output only the title and the Platform section" do
subject.display(out)
- expect(out.out.string).to eq <<-END
-================================================================================
-test title
-================================================================================
-
-System Info:
-------------
-chef_version=1.2.3
-ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
-program_name=chef-client
-executable=/test/bin/chef-client
+ expect(out.out.string).to eq <<~END
+ ================================================================================
+ test title
+ ================================================================================
+
+ System Info:
+ ------------
+ chef_version=1.2.3
+ ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
+ program_name=chef-client
+ executable=/test/bin/chef-client
END
end
@@ -92,21 +92,21 @@ executable=/test/bin/chef-client
it "should output the expected sections" do
subject.display(out)
- expect(out.out.string).to eq <<-END
-================================================================================
-test title
-================================================================================
-
-test heading
-------------
-test text
-
-System Info:
-------------
-chef_version=1.2.3
-ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
-program_name=chef-client
-executable=/test/bin/chef-client
+ expect(out.out.string).to eq <<~END
+ ================================================================================
+ test title
+ ================================================================================
+
+ test heading
+ ------------
+ test text
+
+ System Info:
+ ------------
+ chef_version=1.2.3
+ ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
+ program_name=chef-client
+ executable=/test/bin/chef-client
END
end
@@ -119,19 +119,19 @@ executable=/test/bin/chef-client
# reset on global values.
Chef.set_node({ "platform" => "openvms", "platform_version" => "8.4-2L1" })
subject.display(out)
- expect(out.out.string).to eq <<-END
-================================================================================
-test title
-================================================================================
-
-System Info:
-------------
-chef_version=1.2.3
-platform=openvms
-platform_version=8.4-2L1
-ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
-program_name=chef-client
-executable=/test/bin/chef-client
+ expect(out.out.string).to eq <<~END
+ ================================================================================
+ test title
+ ================================================================================
+
+ System Info:
+ ------------
+ chef_version=1.2.3
+ platform=openvms
+ platform_version=8.4-2L1
+ ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
+ program_name=chef-client
+ executable=/test/bin/chef-client
END
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 2c1da7345b..209d987e78 100644
--- a/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb
+++ b/spec/unit/formatters/error_inspectors/compile_error_inspector_spec.rb
@@ -18,22 +18,22 @@
require "spec_helper"
-BAD_RECIPE = <<-E
-#
-# Cookbook Name:: syntax-err
-# Recipe:: default
-#
-# Copyright 2012-2016, YOUR_COMPANY_NAME
-#
-# All rights reserved - Do Not Redistribute
-#
-
-
-file "/tmp/explode-me" do
- mode 0655
- owner "root"
- this_is_not_a_valid_method
-end
+BAD_RECIPE = <<~E.freeze
+ #
+ # Cookbook Name:: syntax-err
+ # Recipe:: default
+ #
+ # Copyright 2012-2016, YOUR_COMPANY_NAME
+ #
+ # All rights reserved - Do Not Redistribute
+ #
+
+
+ file "/tmp/explode-me" do
+ mode 0655
+ owner "root"
+ this_is_not_a_valid_method
+ end
E
describe Chef::Formatters::ErrorInspectors::CompileErrorInspector do
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..437cc3ee49 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
@@ -22,7 +22,7 @@ describe Chef::Formatters::ErrorInspectors::CookbookSyncErrorInspector do
before do
@description = Chef::Formatters::ErrorDescription.new("Error Expanding RunList:")
@outputter = Chef::Formatters::IndentableOutputStream.new(StringIO.new, STDERR)
- #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
+ # @outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
end
describe "when explaining a 502 error" do
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 93aac417fa..84a3804dc2 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
@@ -19,7 +19,7 @@
require "spec_helper"
# spec_helper loads the shared examples already.
-#require 'support/shared/unit/api_error_inspector_spec'
+# require 'support/shared/unit/api_error_inspector_spec'
describe Chef::Formatters::ErrorInspectors::NodeLoadErrorInspector do
it_behaves_like "an api error inspector"
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 cea93888eb..63a841ccda 100644
--- a/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb
+++ b/spec/unit/formatters/error_inspectors/registration_error_inspector_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
# spec_helper loads the shared examples already.
-#require 'support/shared/unit/api_error_inspector_spec'
+# require 'support/shared/unit/api_error_inspector_spec'
describe Chef::Formatters::ErrorInspectors::RegistrationErrorInspector do
it_behaves_like "an api error inspector"
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 072dcfef28..0cdb06c3b3 100644
--- a/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb
+++ b/spec/unit/formatters/error_inspectors/resource_failure_inspector_spec.rb
@@ -40,7 +40,7 @@ describe Chef::Formatters::ErrorInspectors::ResourceFailureInspector do
@description = Chef::Formatters::ErrorDescription.new("Error Converging Resource:")
@stdout = StringIO.new
@outputter = Chef::Formatters::IndentableOutputStream.new(@stdout, STDERR)
- #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
+ # @outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
allow(Chef::Config).to receive(:cookbook_path).and_return([ "/var/chef/cache" ])
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 3e988c584d..70cf96f7c9 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
@@ -27,7 +27,7 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do
@description = Chef::Formatters::ErrorDescription.new("Error Expanding RunList:")
@outputter = Chef::Formatters::IndentableOutputStream.new(StringIO.new, STDERR)
- #@outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
+ # @outputter = Chef::Formatters::IndentableOutputStream.new(STDOUT, STDERR)
end
describe "when explaining a missing role error" do
@@ -57,7 +57,7 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do
allow(@response).to receive(:body).and_return(@response_body)
@exception = Net::HTTPServerException.new("(exception) forbidden", @response)
@inspector = Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector.new(@node, @exception)
- allow(@inspector).to receive(:config).and_return(:node_name => "unit-test.example.com")
+ allow(@inspector).to receive(:config).and_return(node_name: "unit-test.example.com")
@inspector.add_explanation(@description)
end
@@ -76,9 +76,9 @@ describe Chef::Formatters::ErrorInspectors::RunListExpansionErrorInspector do
@exception = Net::HTTPServerException.new("(exception) unauthorized", @response)
@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")
+ 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")
@inspector.add_explanation(@description)
end
diff --git a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
index 746b343e9c..b2ca8704b0 100644
--- a/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
+++ b/spec/unit/guard_interpreter/resource_guard_interpreter_spec.rb
@@ -106,7 +106,7 @@ describe Chef::GuardInterpreter::ResourceGuardInterpreter do
end
let(:shell_out) do
- instance_double(Mixlib::ShellOut, :live_stream => true, :run_command => true, :error! => nil)
+ instance_double(Mixlib::ShellOut, live_stream: true, run_command: true, error!: nil)
end
before do
@@ -118,7 +118,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 +131,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,7 +145,7 @@ 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
diff --git a/spec/unit/handler/json_file_spec.rb b/spec/unit/handler/json_file_spec.rb
index 4be448690a..f10c6a6701 100644
--- a/spec/unit/handler/json_file_spec.rb
+++ b/spec/unit/handler/json_file_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Handler::JsonFile do
before(:each) do
- @handler = Chef::Handler::JsonFile.new(:the_sun => "will rise", :path => "/tmp/foobarbazqux")
+ @handler = Chef::Handler::JsonFile.new(the_sun: "will rise", path: "/tmp/foobarbazqux")
end
it "accepts arbitrary config options" do
diff --git a/spec/unit/http/api_versions_spec.rb b/spec/unit/http/api_versions_spec.rb
index 2ccb847acc..2b52e87cae 100644
--- a/spec/unit/http/api_versions_spec.rb
+++ b/spec/unit/http/api_versions_spec.rb
@@ -43,7 +43,7 @@ describe Chef::HTTP::APIVersions do
end
let(:response) do
- m = double("HttpResponse", :body => response_body)
+ m = double("HttpResponse", body: response_body)
allow(m).to receive(:key?).with("x-ops-server-api-version").and_return(true)
allow(m).to receive(:code).and_return(return_value)
allow(m).to receive(:[]) do |key|
diff --git a/spec/unit/http/authenticator_spec.rb b/spec/unit/http/authenticator_spec.rb
index 5de39523cf..4a919ad492 100644
--- a/spec/unit/http/authenticator_spec.rb
+++ b/spec/unit/http/authenticator_spec.rb
@@ -20,22 +20,22 @@ require "spec_helper"
require "chef/http/authenticator"
describe Chef::HTTP::Authenticator do
- let(:class_instance) { Chef::HTTP::Authenticator.new }
- let(:method) { double("method") }
- let(:url) { double("url") }
+ let(:class_instance) { Chef::HTTP::Authenticator.new(client_name: "test") }
+ let(:method) { "GET" }
+ let(:url) { URI("https://chef.example.com/organizations/test") }
let(:headers) { Hash.new }
- let(:data) { double("data") }
-
- before do
- allow(class_instance).to receive(:authentication_headers).and_return({})
- end
+ let(:data) { "" }
context "when handle_request is called" do
shared_examples_for "merging the server API version into the headers" do
+ before do
+ allow(class_instance).to receive(:authentication_headers).and_return({})
+ end
+
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 })
+ expect(class_instance.handle_request(method, url, headers, data)[2])
+ .to include({ "X-Ops-Server-API-Version" => Chef::HTTP::Authenticator::DEFAULT_SERVER_API_VERSION })
end
context "when version_class is provided" do
@@ -53,17 +53,17 @@ describe Chef::HTTP::Authenticator do
it "uses it to select the correct http version" do
Chef::ServerAPIVersions.instance.reset!
expect(AuthFactoryClass).to receive(:best_request_version).and_call_original
- expect(class_instance.handle_request(method, url, headers, data)[2]).
- to include({ "X-Ops-Server-API-Version" => "2" })
+ expect(class_instance.handle_request(method, url, headers, data)[2])
+ .to include({ "X-Ops-Server-API-Version" => "2" })
end
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" })
+ expect(class_instance.handle_request(method, url, headers, data)[2])
+ .to include({ "X-Ops-Server-API-Version" => "-10" })
end
end
end
@@ -96,5 +96,30 @@ describe Chef::HTTP::Authenticator do
class_instance.handle_request(method, url, headers, data)
end
end
+
+ context "when ssh_agent_signing" do
+ let(:public_key) { <<~EOH }
+ -----BEGIN PUBLIC KEY-----
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA49TA0y81ps0zxkOpmf5V
+ 4/c4IeR5yVyQFpX3JpxO4TquwnRh8VSUhrw8kkTLmB3cS39Db+3HadvhoqCEbqPE
+ 6915kXSuk/cWIcNozujLK7tkuPEyYVsyTioQAddSdfe+8EhQVf3oHxaKmUd6waXr
+ WqYCnhxgOjxocenREYNhZ/OETIeiPbOku47vB4nJK/0GhKBytL2XnsRgfKgDxf42
+ BqAi1jglIdeq8lAWZNF9TbNBU21AO1iuT7Pm6LyQujhggPznR5FJhXKRUARXBJZa
+ wxpGV4dGtdcahwXNE4601aXPra+xPcRd2puCNoEDBzgVuTSsLYeKBDMSfs173W1Q
+ YwIDAQAB
+ -----END PUBLIC KEY-----
+EOH
+
+ let(:class_instance) { Chef::HTTP::Authenticator.new(client_name: "test", raw_key: public_key, ssh_agent_signing: true) }
+
+ it "sets use_ssh_agent if needed" do
+ expect(Mixlib::Authentication::SignedHeaderAuth).to receive(:signing_object).and_wrap_original { |m, *args|
+ m.call(*args).tap do |signing_obj|
+ expect(signing_obj).to receive(:sign).with(instance_of(OpenSSL::PKey::RSA), use_ssh_agent: true).and_return({})
+ end
+ }
+ class_instance.handle_request(method, url, headers, data)
+ end
+ end
end
end
diff --git a/spec/unit/http/http_request_spec.rb b/spec/unit/http/http_request_spec.rb
index 29562de021..c500c3b99e 100644
--- a/spec/unit/http/http_request_spec.rb
+++ b/spec/unit/http/http_request_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Klaas Jan Wierenga (<k.j.wierenga@gmail.com>)
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -52,6 +52,12 @@ describe Chef::HTTP::HTTPRequest do
expect(request.headers["Host"]).to eql("yourhost.com:8888")
end
+ it "should not mutate the URI when it contains parameters" do
+ # buggy constructor code mutated strings owned by the URI parameter
+ uri = URI("http://dummy.com/foo?bar=baz")
+ request = Chef::HTTP::HTTPRequest.new(:GET, uri, "")
+ expect(uri).to eql(URI("http://dummy.com/foo?bar=baz"))
+ end
end
context "with HTTPS url scheme" do
diff --git a/spec/unit/http/ssl_policies_spec.rb b/spec/unit/http/ssl_policies_spec.rb
index df6dee1198..b67ecc84de 100644
--- a/spec/unit/http/ssl_policies_spec.rb
+++ b/spec/unit/http/ssl_policies_spec.rb
@@ -145,7 +145,7 @@ describe "HTTP SSL Policy" do
# For whatever reason, OpenSSL errors out when adding a
# cert you already have to the certificate store.
ssl_policy.set_custom_certs
- ssl_policy.set_custom_certs #should not raise an error
+ ssl_policy.set_custom_certs # should not raise an error
end
end
end
diff --git a/spec/unit/http/validate_content_length_spec.rb b/spec/unit/http/validate_content_length_spec.rb
index 5067d36d38..673e03f7f4 100644
--- a/spec/unit/http/validate_content_length_spec.rb
+++ b/spec/unit/http/validate_content_length_spec.rb
@@ -44,7 +44,7 @@ describe Chef::HTTP::ValidateContentLength do
end
let(:response) do
- m = double("HttpResponse", :body => response_body)
+ m = double("HttpResponse", body: response_body)
allow(m).to receive(:[]) do |key|
response_headers[key]
end
@@ -67,7 +67,7 @@ describe Chef::HTTP::ValidateContentLength do
data_length = streaming_length
while data_length > 0
chunk_size = data_length > 10 ? 10 : data_length
- stream_handler.handle_chunk(double("Chunk", :bytesize => chunk_size))
+ stream_handler.handle_chunk(double("Chunk", bytesize: chunk_size))
data_length -= chunk_size
end
@@ -85,8 +85,8 @@ describe Chef::HTTP::ValidateContentLength do
before(:each) do
@original_log_level = Chef::Log.level
- Chef::Log.level = :debug
- allow(Chef::Log).to receive(:debug) do |message|
+ Chef::Log.level = :trace
+ allow(Chef::Log).to receive(:trace) do |message|
debug_stream.puts message
end
end
@@ -111,7 +111,7 @@ describe Chef::HTTP::ValidateContentLength do
describe "when running #{req_type} request" do
let(:request_type) { req_type.to_sym }
- it "should skip validation and log for debug" do
+ it "should skip validation and log for trace" do
run_content_length_validation
expect(debug_output).to include("HTTP server did not include a Content-Length header in response")
end
@@ -126,7 +126,7 @@ describe Chef::HTTP::ValidateContentLength do
describe "when running #{req_type} request" do
let(:request_type) { req_type.to_sym }
- it "should skip validation and log for debug" do
+ it "should skip validation and log for trace" do
run_content_length_validation
expect(debug_output).to include("HTTP server responded with a negative Content-Length header (-1), cannot identify truncated downloads.")
end
@@ -180,7 +180,7 @@ describe Chef::HTTP::ValidateContentLength do
describe "when running #{req_type} request" do
let(:request_type) { req_type.to_sym }
- it "should skip validation and log for debug" do
+ it "should skip validation and log for trace" do
run_content_length_validation
expect(debug_output).to include("Transfer-Encoding header is set, skipping Content-Length check.")
end
diff --git a/spec/unit/http_spec.rb b/spec/unit/http_spec.rb
index d58f07c417..bf873b8535 100644
--- a/spec/unit/http_spec.rb
+++ b/spec/unit/http_spec.rb
@@ -93,6 +93,15 @@ describe Chef::HTTP do
expect { http.send(:stream_to_tempfile, uri, resp) }.to raise_error("TestError")
end
+ it "accepts a tempfile" do
+ resp = Net::HTTPOK.new("1.1", 200, "OK")
+ http = Chef::HTTP.new(uri)
+ tempfile = Tempfile.open("tempy-mctempfile")
+ expect(Tempfile).not_to receive(:open)
+ expect(resp).to receive(:read_body).and_yield("conty-mccontent")
+ http.send(:stream_to_tempfile, uri, resp, tempfile)
+ expect(IO.read(tempfile.path)).to eql("conty-mccontent")
+ end
end
describe "head" do
diff --git a/spec/unit/key_spec.rb b/spec/unit/key_spec.rb
index 4af506d227..ea2eae3df7 100644
--- a/spec/unit/key_spec.rb
+++ b/spec/unit/key_spec.rb
@@ -24,16 +24,16 @@ 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
- <<EOS
------BEGIN PUBLIC KEY-----
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvPo+oNPB7uuNkws0fC02
-KxSwdyqPLu0fhI1pOweNKAZeEIiEz2PkybathHWy8snSXGNxsITkf3eyvIIKa8OZ
-WrlqpI3yv/5DOP8HTMCxnFuMJQtDwMcevlqebX4bCxcByuBpNYDcAHjjfLGSfMjn
-E5lZpgYWwnpic4kSjYcL9ORK9nYvlWV9P/kCYmRhIjB4AhtpWRiOfY/TKi3P2LxT
-IjSmiN/ihHtlhV/VSnBJ5PzT/lRknlrJ4kACoz7Pq9jv+aAx5ft/xE9yDa2DYs0q
-Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo
-0wIDAQAB
------END PUBLIC KEY-----
+ <<~EOS
+ -----BEGIN PUBLIC KEY-----
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvPo+oNPB7uuNkws0fC02
+ KxSwdyqPLu0fhI1pOweNKAZeEIiEz2PkybathHWy8snSXGNxsITkf3eyvIIKa8OZ
+ WrlqpI3yv/5DOP8HTMCxnFuMJQtDwMcevlqebX4bCxcByuBpNYDcAHjjfLGSfMjn
+ E5lZpgYWwnpic4kSjYcL9ORK9nYvlWV9P/kCYmRhIjB4AhtpWRiOfY/TKi3P2LxT
+ IjSmiN/ihHtlhV/VSnBJ5PzT/lRknlrJ4kACoz7Pq9jv+aAx5ft/xE9yDa2DYs0q
+ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo
+ 0wIDAQAB
+ -----END PUBLIC KEY-----
EOS
end
@@ -564,7 +564,7 @@ EOS
end
end
- end #update
+ end # update
describe "load" do
shared_examples_for "load" do
@@ -592,7 +592,7 @@ EOS
end
end
- end #load
+ end # load
describe "destroy" do
shared_examples_for "destroy key" do
diff --git a/spec/unit/knife/bootstrap/client_builder_spec.rb b/spec/unit/knife/bootstrap/client_builder_spec.rb
index 97ba0fc48e..f259002b20 100644
--- a/spec/unit/knife/bootstrap/client_builder_spec.rb
+++ b/spec/unit/knife/bootstrap/client_builder_spec.rb
@@ -41,7 +41,7 @@ describe Chef::Knife::Bootstrap::ClientBuilder do
end
context "#sanity_check!" do
- let(:response_404) { OpenStruct.new(:code => "404") }
+ let(:response_404) { OpenStruct.new(code: "404") }
let(:exception_404) { Net::HTTPServerException.new("404 not found", response_404) }
context "in cases where the prompting fails" do
@@ -180,8 +180,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 736ff9b099..624261fb8b 100644
--- a/spec/unit/knife/bootstrap_spec.rb
+++ b/spec/unit/knife/bootstrap_spec.rb
@@ -84,24 +84,20 @@ describe Chef::Knife::Bootstrap do
end
end
- context "with :distro and :bootstrap_template cli options" do
- let(:bootstrap_cli_options) { [ "--bootstrap-template", "my-template", "--distro", "other-template" ] }
-
- it "should select bootstrap template" do
- expect(File.basename(knife.bootstrap_template)).to eq("my-template")
+ context "with --bootstrap-preinstall-command" do
+ command = "while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1; do\n echo 'waiting for dpkg lock';\n sleep 1;\n done;"
+ let(:bootstrap_cli_options) { [ "--bootstrap-preinstall-command", command ] }
+ let(:rendered_template) do
+ knife.merge_configs
+ knife.render_template
end
- end
-
- context "with :distro and :template_file cli options" do
- let(:bootstrap_cli_options) { [ "--distro", "my-template", "--template-file", "other-template" ] }
-
- it "should select bootstrap template" do
- expect(File.basename(knife.bootstrap_template)).to eq("other-template")
+ it "configures the preinstall command in the bootstrap template correctly" do
+ expect(rendered_template).to match(%r{command})
end
end
context "with :bootstrap_template and :template_file cli options" do
- let(:bootstrap_cli_options) { [ "--bootstrap-template", "my-template", "--template-file", "other-template" ] }
+ let(:bootstrap_cli_options) { [ "--bootstrap-template", "my-template", "other-template" ] }
it "should select bootstrap template" do
expect(File.basename(knife.bootstrap_template)).to eq("my-template")
@@ -122,7 +118,7 @@ describe Chef::Knife::Bootstrap do
let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")) }
it "loads the given file as the template" do
- expect(Chef::Log).to receive(:debug)
+ expect(Chef::Log).to receive(:trace)
expect(knife.find_template).to eq(File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")))
end
end
@@ -235,7 +231,7 @@ describe Chef::Knife::Bootstrap do
end
end
- ["-d", "--distro", "-t", "--bootstrap-template", "--template-file"].each do |t|
+ ["-t", "--bootstrap-template"].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"])
@@ -516,6 +512,11 @@ describe Chef::Knife::Bootstrap do
end
context "a flat directory structure" do
+ it "escapes single-quotes" do
+ expect(rendered_template).to match("cat > /etc/chef/client.d/02-strings.rb <<'EOP'")
+ expect(rendered_template).to match("something '\\\\''/foo/bar'\\\\''")
+ end
+
it "creates a file 00-foo.rb" do
expect(rendered_template).to match("cat > /etc/chef/client.d/00-foo.rb <<'EOP'")
expect(rendered_template).to match("d6f9b976-289c-4149-baf7-81e6ffecf228")
diff --git a/spec/unit/knife/client_bulk_delete_spec.rb b/spec/unit/knife/client_bulk_delete_spec.rb
index 994f4d33a4..feebab4986 100644
--- a/spec/unit/knife/client_bulk_delete_spec.rb
+++ b/spec/unit/knife/client_bulk_delete_spec.rb
@@ -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_delete_spec.rb b/spec/unit/knife/client_delete_spec.rb
index b05a487d62..41a83b05e4 100644
--- a/spec/unit/knife/client_delete_spec.rb
+++ b/spec/unit/knife/client_delete_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::ClientDelete do
@knife = Chef::Knife::ClientDelete.new
# defaults
@knife.config = {
- :delete_validators => false,
+ delete_validators: false,
}
@knife.name_args = [ "adam" ]
end
diff --git a/spec/unit/knife/client_reregister_spec.rb b/spec/unit/knife/client_reregister_spec.rb
index 6776cafa0a..6b6519d44f 100644
--- a/spec/unit/knife/client_reregister_spec.rb
+++ b/spec/unit/knife/client_reregister_spec.rb
@@ -22,7 +22,7 @@ describe Chef::Knife::ClientReregister do
before(:each) do
@knife = Chef::Knife::ClientReregister.new
@knife.name_args = [ "adam" ]
- @client_mock = double("client_mock", :private_key => "foo_key")
+ @client_mock = double("client_mock", private_key: "foo_key")
@stdout = StringIO.new
allow(@knife.ui).to receive(:stdout).and_return(@stdout)
end
diff --git a/spec/unit/knife/configure_client_spec.rb b/spec/unit/knife/configure_client_spec.rb
index 0f83897564..c83ceed6cb 100644
--- a/spec/unit/knife/configure_client_spec.rb
+++ b/spec/unit/knife/configure_client_spec.rb
@@ -43,10 +43,10 @@ describe Chef::Knife::ConfigureClient do
@knife.name_args = ["/home/bob/.chef"]
@client_file = StringIO.new
@validation_file = StringIO.new
- expect(File).to receive(:open).with("/home/bob/.chef/client.rb", "w").
- and_yield(@client_file)
- expect(File).to receive(:open).with("/home/bob/.chef/validation.pem", "w").
- and_yield(@validation_file)
+ expect(File).to receive(:open).with("/home/bob/.chef/client.rb", "w")
+ .and_yield(@client_file)
+ expect(File).to receive(:open).with("/home/bob/.chef/validation.pem", "w")
+ .and_yield(@validation_file)
expect(IO).to receive(:read).and_return("foo_bar_baz")
end
diff --git a/spec/unit/knife/configure_spec.rb b/spec/unit/knife/configure_spec.rb
index b7802d3890..1cdad0cd0e 100644
--- a/spec/unit/knife/configure_spec.rb
+++ b/spec/unit/knife/configure_spec.rb
@@ -6,7 +6,7 @@ describe Chef::Knife::Configure do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::Configure.new
- @rest_client = double("null rest client", :post => { :result => :true })
+ @rest_client = double("null rest client", post: { result: :true })
allow(@knife).to receive(:rest).and_return(@rest_client)
@out = StringIO.new
@@ -26,8 +26,7 @@ describe Chef::Knife::Configure do
let(:ohai) do
o = {}
- allow(o).to receive(:require_plugin)
- allow(o).to receive(:load_plugins)
+ allow(o).to receive(:all_plugins).with(%w{ os hostname fqdn })
o[:fqdn] = fqdn
o
end
@@ -124,55 +123,12 @@ describe Chef::Knife::Configure do
end
end
- it "asks the user for the location of a chef repo" do
- @knife.ask_user_for_config
- expect(@out.string).to match(Regexp.escape("Please enter the path to a chef repository (or leave blank):"))
- expect(@knife.chef_repo).to eq("")
- end
-
- it "asks the users for the name of the validation client" do
- @knife.ask_user_for_config
- expect(@out.string).to match(Regexp.escape("Please enter the validation clientname: [chef-validator]"))
- expect(@knife.validation_client_name).to eq("chef-validator")
- end
-
- it "should not ask the users for the name of the validation client if --validation_client_name is specified" do
- @knife.config[:validation_client_name] = "my-validator"
- @knife.ask_user_for_config
- expect(@out.string).not_to match(Regexp.escape("Please enter the validation clientname:"))
- expect(@knife.validation_client_name).to eq("my-validator")
- end
-
- it "asks the users for the location of the validation key" do
- @knife.ask_user_for_config
- expect(@out.string).to match(Regexp.escape("Please enter the location of the validation key: [#{default_validator_key}]"))
- if windows?
- expect(@knife.validation_key.capitalize).to eq(default_validator_key_win32.capitalize)
- else
- expect(@knife.validation_key).to eq(default_validator_key)
- end
- end
-
- it "should not ask the users for the location of the validation key if --validation_key is specified" do
- @knife.config[:validation_key] = "/home/you/.chef/my-validation.pem"
- @knife.ask_user_for_config
- expect(@out.string).not_to match(Regexp.escape("Please enter the location of the validation key:"))
- if windows?
- expect(@knife.validation_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$}
- else
- expect(@knife.validation_key).to eq("/home/you/.chef/my-validation.pem")
- end
- end
-
it "should not ask the user for anything if -i and all other properties are specified" do
@knife.config[:initial] = true
@knife.config[:chef_server_url] = "http://localhost:5000"
@knife.config[:node_name] = "testnode"
@knife.config[:admin_client_name] = "my-webui"
@knife.config[:admin_client_key] = "/home/you/.chef/my-webui.pem"
- @knife.config[:validation_client_name] = "my-validator"
- @knife.config[:validation_key] = "/home/you/.chef/my-validation.pem"
- @knife.config[:repository] = ""
@knife.config[:client_key] = "/home/you/a-new-user.pem"
allow(Etc).to receive(:getlogin).and_return("a-new-user")
@@ -184,40 +140,33 @@ describe Chef::Knife::Configure do
expect(@knife.admin_client_name).to eq("my-webui")
if windows?
expect(@knife.admin_client_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-webui\.pem$}
- expect(@knife.validation_key).to match %r{^[A-Za-z]:/home/you/\.chef/my-validation\.pem$}
expect(@knife.new_client_key).to match %r{^[A-Za-z]:/home/you/a-new-user\.pem$}
else
expect(@knife.admin_client_key).to eq("/home/you/.chef/my-webui.pem")
- expect(@knife.validation_key).to eq("/home/you/.chef/my-validation.pem")
expect(@knife.new_client_key).to eq("/home/you/a-new-user.pem")
end
- expect(@knife.validation_client_name).to eq("my-validator")
- expect(@knife.chef_repo).to eq("")
end
it "writes the new data to a config file" do
- allow(File).to receive(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb")
+ allow(Chef::Util::PathHelper).to receive(:home).with(".chef").and_return("/home/you/.chef")
+ allow(File).to receive(:expand_path).with("/home/you/.chef/credentials").and_return("/home/you/.chef/credentials")
allow(File).to receive(:expand_path).with("/home/you/.chef/#{Etc.getlogin}.pem").and_return("/home/you/.chef/#{Etc.getlogin}.pem")
- allow(File).to receive(:expand_path).with(default_validator_key).and_return(default_validator_key)
allow(File).to receive(:expand_path).with(default_admin_key).and_return(default_admin_key)
expect(FileUtils).to receive(:mkdir_p).with("/home/you/.chef")
config_file = StringIO.new
- expect(::File).to receive(:open).with("/home/you/.chef/knife.rb", "w").and_yield config_file
+ expect(::File).to receive(:open).with("/home/you/.chef/credentials", "w").and_yield config_file
@knife.config[:repository] = "/home/you/chef-repo"
@knife.run
- expect(config_file.string).to match(/^node_name[\s]+'#{Etc.getlogin}'$/)
- expect(config_file.string).to match(%r{^client_key[\s]+'/home/you/.chef/#{Etc.getlogin}.pem'$})
- expect(config_file.string).to match(/^validation_client_name\s+'chef-validator'$/)
- expect(config_file.string).to match(%r{^validation_key\s+'#{default_validator_key}'$})
- expect(config_file.string).to match(%r{^chef_server_url\s+'#{default_server_url}'$})
- expect(config_file.string).to match(%r{cookbook_path\s+\[ '/home/you/chef-repo/cookbooks' \]})
+ expect(config_file.string).to match(/^client_name[\s]+=[\s]+'#{Etc.getlogin}'$/)
+ expect(config_file.string).to match(%r{^client_key[\s]+=[\s]+'/home/you/.chef/#{Etc.getlogin}.pem'$})
+ expect(config_file.string).to match(%r{^chef_server_url\s+=[\s]+'#{default_server_url}'$})
end
it "creates a new client when given the --initial option" do
- expect(File).to receive(:expand_path).with("/home/you/.chef/knife.rb").and_return("/home/you/.chef/knife.rb")
+ allow(Chef::Util::PathHelper).to receive(:home).with(".chef").and_return("/home/you/.chef")
+ expect(File).to receive(:expand_path).with("/home/you/.chef/credentials").and_return("/home/you/.chef/credentials")
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)
+ allow(File).to receive(:expand_path).with(default_admin_key).and_return(default_admin_key)
Chef::Config[:node_name] = "webmonkey.example.com"
user_command = Chef::Knife::UserCreate.new
@@ -227,7 +176,7 @@ describe Chef::Knife::Configure do
allow(Chef::Knife::UserCreate).to receive(:new).and_return(user_command)
expect(FileUtils).to receive(:mkdir_p).with("/home/you/.chef")
- expect(::File).to receive(:open).with("/home/you/.chef/knife.rb", "w")
+ expect(::File).to receive(:open).with("/home/you/.chef/credentials", "w")
@knife.config[:initial] = true
@knife.config[:user_password] = "blah"
@knife.run
diff --git a/spec/unit/knife/cookbook_bulk_delete_spec.rb b/spec/unit/knife/cookbook_bulk_delete_spec.rb
index 62b8c9fe51..c8c1873081 100644
--- a/spec/unit/knife/cookbook_bulk_delete_spec.rb
+++ b/spec/unit/knife/cookbook_bulk_delete_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Knife::CookbookBulkDelete do
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
diff --git a/spec/unit/knife/cookbook_delete_spec.rb b/spec/unit/knife/cookbook_delete_spec.rb
index 9bf4c81a73..7277b63c28 100644
--- a/spec/unit/knife/cookbook_delete_spec.rb
+++ b/spec/unit/knife/cookbook_delete_spec.rb
@@ -62,8 +62,8 @@ describe Chef::Knife::CookbookDelete do
describe "with -p or --purge" 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.+/)
+ expect(@knife).to receive(:confirm)
+ .with(/.+Are you sure you want to purge files.+/)
expect(@knife).to receive(:delete_without_explicit_version)
@knife.run
end
@@ -146,8 +146,8 @@ describe Chef::Knife::CookbookDelete do
describe "if the cookbook can't be found" do
before(:each) do
- expect(@rest_mock).to receive(:get).
- and_raise(Net::HTTPServerException.new("404 Not Found", "404"))
+ expect(@rest_mock).to receive(:get)
+ .and_raise(Net::HTTPServerException.new("404 Not Found", "404"))
end
it "should print an error" do
diff --git a/spec/unit/knife/cookbook_download_spec.rb b/spec/unit/knife/cookbook_download_spec.rb
index 1fb995f71d..122c284b93 100644
--- a/spec/unit/knife/cookbook_download_spec.rb
+++ b/spec/unit/knife/cookbook_download_spec.rb
@@ -47,13 +47,13 @@ describe Chef::Knife::CookbookDownload do
@rest_mock = double("rest")
allow(@knife).to receive(:rest).and_return(@rest_mock)
- expect(Chef::CookbookVersion).to receive(:load).with("foobar", "1.0.0").
- and_return(cookbook)
+ expect(Chef::CookbookVersion).to receive(:load).with("foobar", "1.0.0")
+ .and_return(cookbook)
end
let(:manifest_data) do
{
- :all_files => [
+ all_files: [
{
"path" => "recipes/foo.rb",
"name" => "recipes/foo.rb",
@@ -119,18 +119,18 @@ describe Chef::Knife::CookbookDownload do
describe "when downloading the cookbook" 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)
+ expect(FileUtils).to receive(:mkdir_p).with("/var/tmp/chef/foobar-1.0.0/#{dir}")
+ .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)
+ expect(@rest_mock).to receive(:streaming_request).with("http://example.org/files/#{file}")
+ .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}")
+ expect(FileUtils).to receive(:mv)
+ .with("/var/tmp/#{File.basename(f)}", "/var/tmp/chef/foobar-1.0.0/#{f}")
end
end
@@ -182,8 +182,8 @@ describe Chef::Knife::CookbookDownload do
describe "with -N or --latest" 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"])
+ expect(@knife).to receive(:available_versions).at_least(:once)
+ .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
@@ -196,26 +196,26 @@ describe Chef::Knife::CookbookDownload do
end
it "should return nil if there are no versions" do
- expect(Chef::CookbookVersion).to receive(:available_versions).
- with("foobar").
- and_return(nil)
+ expect(Chef::CookbookVersion).to receive(:available_versions)
+ .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"])
+ expect(Chef::CookbookVersion).to receive(:available_versions)
+ .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")])
end
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"])
+ expect(Chef::CookbookVersion).to receive(:available_versions)
+ .once
+ .with("foobar")
+ .and_return(["1.1.0", "2.0.0", "1.0.0"])
@knife.available_versions
@knife.available_versions
end
diff --git a/spec/unit/knife/cookbook_list_spec.rb b/spec/unit/knife/cookbook_list_spec.rb
index fce6bc9593..e34b58b672 100644
--- a/spec/unit/knife/cookbook_list_spec.rb
+++ b/spec/unit/knife/cookbook_list_spec.rb
@@ -37,8 +37,8 @@ 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)
+ expect(@rest_mock).to receive(:get).with("/cookbooks?num_versions=1")
+ .and_return(@cookbook_data)
@knife.run
@cookbook_names.each do |item|
expect(@stdout.string).to match /#{item}\s+1\.0\.1/
@@ -47,9 +47,9 @@ 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)
+ expect(@rest_mock).to receive(:get)
+ .with("/environments/production/cookbooks?num_versions=1")
+ .and_return(@cookbook_data)
@knife.run
end
@@ -75,8 +75,8 @@ describe Chef::Knife::CookbookList do
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)
+ expect(@rest_mock).to receive(:get).with("/cookbooks?num_versions=all")
+ .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/
diff --git a/spec/unit/knife/cookbook_show_spec.rb b/spec/unit/knife/cookbook_show_spec.rb
index bd952c215f..6642e0690d 100644
--- a/spec/unit/knife/cookbook_show_spec.rb
+++ b/spec/unit/knife/cookbook_show_spec.rb
@@ -49,10 +49,10 @@ describe Chef::Knife::CookbookShow do
{
"all_files" => [
{
- :name => "recipes/default.rb",
- :path => "recipes/default.rb",
- :checksum => "1234",
- :url => "http://example.org/files/default.rb",
+ name: "recipes/default.rb",
+ path: "recipes/default.rb",
+ checksum: "1234",
+ url: "http://example.org/files/default.rb",
},
],
}
@@ -172,32 +172,32 @@ describe Chef::Knife::CookbookShow do
cb.manifest = {
"all_files" => [
{
- :name => "files/afile.rb",
- :path => "files/host-examplehost.example.org/afile.rb",
- :checksum => "1111",
- :specificity => "host-examplehost.example.org",
- :url => "http://example.org/files/1111",
+ name: "files/afile.rb",
+ path: "files/host-examplehost.example.org/afile.rb",
+ checksum: "1111",
+ specificity: "host-examplehost.example.org",
+ url: "http://example.org/files/1111",
},
{
- :name => "files/afile.rb",
- :path => "files/ubuntu-9.10/afile.rb",
- :checksum => "2222",
- :specificity => "ubuntu-9.10",
- :url => "http://example.org/files/2222",
+ name: "files/afile.rb",
+ path: "files/ubuntu-9.10/afile.rb",
+ checksum: "2222",
+ specificity: "ubuntu-9.10",
+ url: "http://example.org/files/2222",
},
{
- :name => "files/afile.rb",
- :path => "files/ubuntu/afile.rb",
- :checksum => "3333",
- :specificity => "ubuntu",
- :url => "http://example.org/files/3333",
+ name: "files/afile.rb",
+ path: "files/ubuntu/afile.rb",
+ checksum: "3333",
+ specificity: "ubuntu",
+ url: "http://example.org/files/3333",
},
{
- :name => "files/afile.rb",
- :path => "files/default/afile.rb",
- :checksum => "4444",
- :specificity => "default",
- :url => "http://example.org/files/4444",
+ name: "files/afile.rb",
+ path: "files/default/afile.rb",
+ checksum: "4444",
+ specificity: "default",
+ url: "http://example.org/files/4444",
},
],
}
diff --git a/spec/unit/knife/cookbook_test_spec.rb b/spec/unit/knife/cookbook_test_spec.rb
index f8b212e271..dd5d4f096a 100644
--- a/spec/unit/knife/cookbook_test_spec.rb
+++ b/spec/unit/knife/cookbook_test_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Stephen Delano (<stephen@chef.io>)$
# Author:: Matthew Kent (<mkent@magoazul.com>)
-# Copyright:: Copyright 2010-2016, Chef Software Inc.$
+# Copyright:: Copyright 2010-2018, Chef Software Inc.$
# Copyright:: Copyright 2010-2016, Matthew Kent
# License:: Apache License, Version 2.0
#
@@ -73,7 +73,7 @@ describe Chef::Knife::CookbookTest do
@loader[cookbook.name] = cookbook
end
allow(@knife).to receive(:cookbook_loader).and_return(@loader)
- @loader.each do |key, cookbook|
+ @loader.each_value do |cookbook|
expect(@knife).to receive(:test_cookbook).with(cookbook.name)
end
@knife.run
diff --git a/spec/unit/knife/cookbook_upload_spec.rb b/spec/unit/knife/cookbook_upload_spec.rb
index 9e07497c57..74612f520d 100644
--- a/spec/unit/knife/cookbook_upload_spec.rb
+++ b/spec/unit/knife/cookbook_upload_spec.rb
@@ -36,7 +36,7 @@ describe Chef::Knife::CookbookUpload do
cookbook_loader
end
- let(:cookbook_uploader) { double(:upload_cookbooks => nil) }
+ let(:cookbook_uploader) { double(upload_cookbooks: nil) }
let(:output) { StringIO.new }
@@ -61,16 +61,16 @@ describe Chef::Knife::CookbookUpload do
test_cookbook = Chef::CookbookVersion.new("test_cookbook", "/tmp/blah")
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))
+ expect(Chef::CookbookUploader).to receive(:new)
+ .with( kind_of(Array), { force: nil, concurrency: 3 })
+ .and_return(double("Chef::CookbookUploader", upload_cookbooks: true))
knife.run
end
end
describe "run" do
before(:each) do
- allow(Chef::CookbookUploader).to receive_messages(:new => cookbook_uploader)
+ allow(Chef::CookbookUploader).to receive_messages(new: cookbook_uploader)
allow(Chef::CookbookVersion).to receive(:list_all_versions).and_return({})
end
@@ -106,22 +106,22 @@ describe Chef::Knife::CookbookUpload 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} })
+ allow(cookbook_loader).to receive(:merged_cookbook_paths)
+ .and_return({ "test_cookbook" => %w{/path/one/test_cookbook /path/two/test_cookbook} })
end
it "emits a warning" do
knife.run
- 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.
-
-IMPORTANT: In a future version of Chef, this behavior will be removed and you will no longer
-be able to have the same version of a cookbook in multiple places in your cookbook_path.
-WARNING: The affected cookbooks are located:
-test_cookbook:
- /path/one/test_cookbook
- /path/two/test_cookbook
+ 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.
+
+ IMPORTANT: In a future version of Chef, this behavior will be removed and you will no longer
+ be able to have the same version of a cookbook in multiple places in your cookbook_path.
+ WARNING: The affected cookbooks are located:
+ test_cookbook:
+ /path/one/test_cookbook
+ /path/two/test_cookbook
E
expect(output.string).to include(expected_message)
end
@@ -310,8 +310,8 @@ E
describe "when a frozen cookbook exists on the server" do
it "should fail to replace it" do
exception = Chef::Exceptions::CookbookFrozen.new
- expect(cookbook_uploader).to receive(:upload_cookbooks).
- and_raise(exception)
+ expect(cookbook_uploader).to receive(:upload_cookbooks)
+ .and_raise(exception)
allow(knife.ui).to receive(:error)
expect(knife.ui).to receive(:error).with(exception)
expect { knife.run }.to raise_error(SystemExit)
diff --git a/spec/unit/knife/core/bootstrap_context_spec.rb b/spec/unit/knife/core/bootstrap_context_spec.rb
index 3a32155063..bd48709a93 100644
--- a/spec/unit/knife/core/bootstrap_context_spec.rb
+++ b/spec/unit/knife/core/bootstrap_context_spec.rb
@@ -26,15 +26,15 @@ 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
{
- :config_log_level => "info",
- :config_log_location => "/tmp/log",
- :validation_key => File.join(CHEF_SPEC_DATA, "ssl", "private_key.pem"),
- :chef_server_url => "http://chef.example.com:4444",
- :validation_client_name => "chef-validator-testing",
+ config_log_level: "info",
+ config_log_location: "/tmp/log",
+ validation_key: File.join(CHEF_SPEC_DATA, "ssl", "private_key.pem"),
+ chef_server_url: "http://chef.example.com:4444",
+ validation_client_name: "chef-validator-testing",
}
end
@@ -51,14 +51,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
@@ -69,25 +69,25 @@ describe Chef::Knife::Core::BootstrapContext do
end
it "generates the config file data" do
- expected = <<-EXPECTED
-chef_server_url "http://chef.example.com:4444"
-validation_client_name "chef-validator-testing"
-log_level :info
-log_location "/tmp/log"
-# Using default node name (fqdn)
+ expected = <<~EXPECTED
+ chef_server_url "http://chef.example.com:4444"
+ validation_client_name "chef-validator-testing"
+ log_level :info
+ log_location "/tmp/log"
+ # Using default node name (fqdn)
EXPECTED
expect(bootstrap_context.config_content).to eq 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"]))
@@ -96,36 +96,36 @@ 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
@@ -159,7 +159,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
@@ -171,7 +171,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
@@ -195,7 +195,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
@@ -204,7 +204,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")
@@ -238,7 +238,7 @@ EXPECTED
describe "when configured in config" do
let(:chef_config) do
{
- :knife => { :verify_api_cert => :false },
+ knife: { verify_api_cert: :false },
}
end
@@ -247,7 +247,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")
@@ -262,7 +262,7 @@ 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")
@@ -272,49 +272,49 @@ EXPECTED
describe "#config_log_location" do
context "when config_log_location is nil" do
- let(:chef_config) { { :config_log_location => nil } }
+ let(:chef_config) { { config_log_location: nil } }
it "sets the default config_log_location in the client.rb" do
expect(bootstrap_context.get_log_location).to eq "STDOUT"
end
end
context "when config_log_location is empty" do
- let(:chef_config) { { :config_log_location => "" } }
+ let(:chef_config) { { config_log_location: "" } }
it "sets the default config_log_location in the client.rb" do
expect(bootstrap_context.get_log_location).to eq "STDOUT"
end
end
context "when config_log_location is :win_evt" do
- let(:chef_config) { { :config_log_location => :win_evt } }
+ let(:chef_config) { { config_log_location: :win_evt } }
it "raise error when config_log_location is :win_evt " do
expect { bootstrap_context.get_log_location }.to raise_error("The value :win_evt is not supported for config_log_location on Linux Platforms \n")
end
end
context "when config_log_location is :syslog" do
- let(:chef_config) { { :config_log_location => :syslog } }
+ let(:chef_config) { { config_log_location: :syslog } }
it "sets the config_log_location value as :syslog in the client.rb" do
expect(bootstrap_context.get_log_location).to eq ":syslog"
end
end
context "When config_log_location is STDOUT" do
- let(:chef_config) { { :config_log_location => STDOUT } }
+ let(:chef_config) { { config_log_location: STDOUT } }
it "Sets the config_log_location value as STDOUT in the client.rb" do
expect(bootstrap_context.get_log_location).to eq "STDOUT"
end
end
context "when config_log_location is STDERR" do
- let(:chef_config) { { :config_log_location => STDERR } }
+ let(:chef_config) { { config_log_location: STDERR } }
it "sets the config_log_location value as STDERR in the client.rb" do
expect(bootstrap_context.get_log_location).to eq "STDERR"
end
end
context "when config_log_location is a path" do
- let(:chef_config) { { :config_log_location => "/tmp/ChefLogFile" } }
+ let(:chef_config) { { config_log_location: "/tmp/ChefLogFile" } }
it "sets the config_log_location path in the client.rb" do
expect(bootstrap_context.get_log_location).to eq "\"/tmp/ChefLogFile\""
end
diff --git a/spec/unit/knife/core/cookbook_scm_repo_spec.rb b/spec/unit/knife/core/cookbook_scm_repo_spec.rb
index 3c16f93533..a530dbcdaa 100644
--- a/spec/unit/knife/core/cookbook_scm_repo_spec.rb
+++ b/spec/unit/knife/core/cookbook_scm_repo_spec.rb
@@ -24,7 +24,7 @@ describe Chef::Knife::CookbookSCMRepo do
@repo_path = File.join(CHEF_SPEC_DATA, "cookbooks")
@stdout, @stderr, @stdin = StringIO.new, StringIO.new, StringIO.new
@ui = Chef::Knife::UI.new(@stdout, @stderr, @stdin, {})
- @cookbook_repo = Chef::Knife::CookbookSCMRepo.new(@repo_path, @ui, :default_branch => "master")
+ @cookbook_repo = Chef::Knife::CookbookSCMRepo.new(@repo_path, @ui, default_branch: "master")
@branch_list = Mixlib::ShellOut.new
@branch_list.stdout.replace(<<-BRANCHES)
@@ -69,7 +69,7 @@ BRANCHES
it "exits when the default branch doesn't exist" do
@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).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@nobranches)
expect { @cookbook_repo.sanity_check }.to raise_error(SystemExit)
end
@@ -77,7 +77,7 @@ BRANCHES
before do
@master_branch = Mixlib::ShellOut.new
@master_branch.stdout.replace "* master\n"
- expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@master_branch)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@master_branch)
end
it "exits when the git repo is dirty" do
@@ -85,14 +85,14 @@ BRANCHES
@dirty_status.stdout.replace(<<-DIRTY)
M chef/lib/chef/knife/cookbook_site_install.rb
DIRTY
- expect(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain", :cwd => @repo_path).and_return(@dirty_status)
+ 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)
end
describe "and the repo is clean" do
before do
@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)
+ 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
@@ -106,35 +106,35 @@ DIRTY
end
it "resets to default state by checking out the default branch" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git checkout master", :cwd => @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git checkout master", cwd: @repo_path)
@cookbook_repo.reset_to_default_state
end
it "determines if a the pristine copy branch exists" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@branch_list)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@branch_list)
expect(@cookbook_repo.branch_exists?("chef-vendor-apache2")).to be_truthy
- expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@branch_list)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@branch_list)
expect(@cookbook_repo.branch_exists?("chef-vendor-nginx")).to be_falsey
end
it "determines if a the branch not exists correctly without substring search" do
- expect(@cookbook_repo).to receive(:shell_out!).twice.with("git branch --no-color", :cwd => @repo_path).and_return(@branch_list)
+ expect(@cookbook_repo).to receive(:shell_out!).twice.with("git branch --no-color", cwd: @repo_path).and_return(@branch_list)
expect(@cookbook_repo).not_to be_branch_exists("chef-vendor-absent")
expect(@cookbook_repo).to be_branch_exists("chef-vendor-absent-new")
end
describe "when the pristine copy branch does not exist" do
it "prepares for import by creating the pristine copy branch" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@branch_list)
- expect(@cookbook_repo).to receive(:shell_out!).with("git checkout -b chef-vendor-nginx", :cwd => @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@branch_list)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git checkout -b chef-vendor-nginx", cwd: @repo_path)
@cookbook_repo.prepare_to_import("nginx")
end
end
describe "when the pristine copy branch does exist" do
it "prepares for import by checking out the pristine copy branch" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", :cwd => @repo_path).and_return(@branch_list)
- expect(@cookbook_repo).to receive(:shell_out!).with("git checkout chef-vendor-apache2", :cwd => @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git branch --no-color", cwd: @repo_path).and_return(@branch_list)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git checkout chef-vendor-apache2", cwd: @repo_path)
@cookbook_repo.prepare_to_import("apache2")
end
end
@@ -143,7 +143,7 @@ DIRTY
before do
@updates = Mixlib::ShellOut.new
@updates.stdout.replace("\n")
- allow(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain -- apache2", :cwd => @repo_path).and_return(@updates)
+ allow(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain -- apache2", cwd: @repo_path).and_return(@updates)
end
it "shows no changes in the pristine copy" do
@@ -159,7 +159,7 @@ DIRTY
before do
@updates = Mixlib::ShellOut.new
@updates.stdout.replace(" M cookbooks/apache2/recipes/default.rb\n")
- allow(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain -- apache2", :cwd => @repo_path).and_return(@updates)
+ allow(@cookbook_repo).to receive(:shell_out!).with("git status --porcelain -- apache2", cwd: @repo_path).and_return(@updates)
end
it "shows changes in the pristine copy" do
@@ -167,20 +167,20 @@ DIRTY
end
it "commits the changes to the repo and tags the commit" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git add apache2", :cwd => @repo_path)
- expect(@cookbook_repo).to receive(:shell_out!).with("git commit -m \"Import apache2 version 1.2.3\" -- apache2", :cwd => @repo_path)
- expect(@cookbook_repo).to receive(:shell_out!).with("git tag -f cookbook-site-imported-apache2-1.2.3", :cwd => @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git add apache2", cwd: @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git commit -m \"Import apache2 version 1.2.3\" -- apache2", cwd: @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git tag -f cookbook-site-imported-apache2-1.2.3", cwd: @repo_path)
expect(@cookbook_repo.finalize_updates_to("apache2", "1.2.3")).to be_truthy
end
end
describe "when a custom default branch is specified" do
before do
- @cookbook_repo = Chef::Knife::CookbookSCMRepo.new(@repo_path, @ui, :default_branch => "develop")
+ @cookbook_repo = Chef::Knife::CookbookSCMRepo.new(@repo_path, @ui, default_branch: "develop")
end
it "resets to default state by checking out the default branch" do
- expect(@cookbook_repo).to receive(:shell_out!).with("git checkout develop", :cwd => @repo_path)
+ expect(@cookbook_repo).to receive(:shell_out!).with("git checkout develop", cwd: @repo_path)
@cookbook_repo.reset_to_default_state
end
end
diff --git a/spec/unit/knife/core/gem_glob_loader_spec.rb b/spec/unit/knife/core/gem_glob_loader_spec.rb
index 2f9e04769e..689426de1b 100644
--- a/spec/unit/knife/core/gem_glob_loader_spec.rb
+++ b/spec/unit/knife/core/gem_glob_loader_spec.rb
@@ -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_value { |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_value { |abs_path| expect(abs_path).to match(%r{chef/knife/.+}) }
end
it "finds user-specific subcommands in the user's ~/.chef directory" do
diff --git a/spec/unit/knife/core/hashed_command_loader_spec.rb b/spec/unit/knife/core/hashed_command_loader_spec.rb
index 53bd81f4f7..e866f13a9c 100644
--- a/spec/unit/knife/core/hashed_command_loader_spec.rb
+++ b/spec/unit/knife/core/hashed_command_loader_spec.rb
@@ -65,7 +65,7 @@ describe Chef::Knife::SubcommandLoader::HashedCommandLoader do
end
it "lists all commands by category when no argument is given" do
- expect(Chef::Log).to receive(:error).with(/There are files specified in the manifest that are missing/)
+ expect(Chef::Log).to receive(:error).with(/There are plugin files specified in the knife cache that cannot be found/)
expect(Chef::Log).to receive(:error).with("Missing files:\n\t/file/for/plugin/b")
expect(loader.list_commands).to eq({})
end
diff --git a/spec/unit/knife/core/node_editor_spec.rb b/spec/unit/knife/core/node_editor_spec.rb
index ce169a77dd..a3dd63177d 100644
--- a/spec/unit/knife/core/node_editor_spec.rb
+++ b/spec/unit/knife/core/node_editor_spec.rb
@@ -55,7 +55,7 @@ describe Chef::Knife::NodeEditor do
context "when config[:all_attributes] == true" do
let(:config) { base_config.merge(all_attributes: true) }
- it 'returns a Hash with all of the node\'s properties' do
+ it "returns a Hash with all of the node's properties" do
expect(subject.view).to eq(node_data)
end
end
@@ -100,10 +100,10 @@ describe Chef::Knife::NodeEditor do
expect(updated_node).to be_a(Chef::Node)
# Expected to have been changed
- expect(updated_node.chef_environment).to eql(updated_data["chef_environment"])
expect(updated_node.normal_attrs).to eql(updated_data["normal"])
expect(updated_node.policy_name).to eql(updated_data["policy_name"])
expect(updated_node.policy_group).to eql(updated_data["policy_group"])
+ expect(updated_node.chef_environment).to eql(updated_data["policy_group"])
expect(updated_node.run_list.map(&:to_s)).to eql(updated_data["run_list"])
# Expected not to have changed
@@ -131,7 +131,7 @@ describe Chef::Knife::NodeEditor do
updated_node = subject.apply_updates(updated_data)
expect(updated_node).to be_a(Chef::Node)
- expect(updated_node.chef_environment).to eql(updated_data["chef_environment"])
+ expect(updated_node.chef_environment).to eql(updated_data["policy_group"])
expect(updated_node.automatic_attrs).to eql(updated_data["automatic"])
expect(updated_node.normal_attrs).to eql(updated_data["normal"])
expect(updated_node.default_attrs).to eql(updated_data["default"])
@@ -173,7 +173,7 @@ describe Chef::Knife::NodeEditor do
end
it "returns an array of the changed property names" do
- expect(subject.updated?).to eql %w{ normal policy_name policy_group run_list }
+ expect(subject.updated?).to eql %w{ chef_environment normal policy_name policy_group run_list }
end
end
@@ -188,9 +188,9 @@ describe Chef::Knife::NodeEditor do
subject.edit_node
end
- it 'returns an array of property names that doesn\'t include ' +
+ it "returns an array of property names that doesn't include " +
"the non-editable properties" do
- expect(subject.updated?).to eql %w{ normal policy_name policy_group run_list }
+ expect(subject.updated?).to eql %w{ chef_environment normal policy_name policy_group run_list }
end
end
end
diff --git a/spec/unit/knife/core/object_loader_spec.rb b/spec/unit/knife/core/object_loader_spec.rb
index 9cabf2ba63..6eb392acae 100644
--- a/spec/unit/knife/core/object_loader_spec.rb
+++ b/spec/unit/knife/core/object_loader_spec.rb
@@ -57,7 +57,7 @@ describe Chef::Knife::Core::ObjectLoader do
it_behaves_like "Chef object", chef_class
end
- #NOTE: This is check for the bug described at CHEF-2352
+ # NOTE: This is check for the bug described at CHEF-2352
describe "when the file is a JSON" do
describe "and it has defined 'json_class'" do
before do
diff --git a/spec/unit/knife/core/ui_spec.rb b/spec/unit/knife/core/ui_spec.rb
index 0b986258b7..025c1ecd91 100644
--- a/spec/unit/knife/core/ui_spec.rb
+++ b/spec/unit/knife/core/ui_spec.rb
@@ -25,10 +25,10 @@ describe Chef::Knife::UI do
before do
@out, @err, @in = StringIO.new, StringIO.new, StringIO.new
@config = {
- :verbosity => 0,
- :yes => nil,
- :format => "summary",
- :field_separator => ".",
+ verbosity: 0,
+ yes: nil,
+ format: "summary",
+ field_separator: ".",
}
@ui = Chef::Knife::UI.new(@out, @err, @in, @config)
end
@@ -171,12 +171,12 @@ describe Chef::Knife::UI do
describe "format_list_for_display" do
it "should print the full hash if --with-uri is true" do
@ui.config[:with_uri] = true
- expect(@ui.format_list_for_display({ :marcy => :playground })).to eq({ :marcy => :playground })
+ expect(@ui.format_list_for_display({ marcy: :playground })).to eq({ marcy: :playground })
end
it "should print only the keys if --with-uri is false" do
@ui.config[:with_uri] = false
- expect(@ui.format_list_for_display({ :marcy => :playground })).to eq([ :marcy ])
+ expect(@ui.format_list_for_display({ marcy: :playground })).to eq([ :marcy ])
end
end
@@ -211,9 +211,9 @@ describe Chef::Knife::UI do
it "formats hashes appropriately" do
@ui.output({ "hi" => "a", "lo" => "b" })
- expect(@out.string).to eq <<EOM
-hi: a
-lo: b
+ expect(@out.string).to eq <<~EOM
+ hi: a
+ lo: b
EOM
end
@@ -224,9 +224,9 @@ EOM
it "formats arrays appropriately" do
@ui.output(%w{a b})
- expect(@out.string).to eq <<EOM
-a
-b
+ expect(@out.string).to eq <<~EOM
+ a
+ b
EOM
end
@@ -247,74 +247,74 @@ EOM
it "formats nested arrays appropriately" do
@ui.output([ %w{a b}, %w{c d}])
- expect(@out.string).to eq <<EOM
-a
-b
+ expect(@out.string).to eq <<~EOM
+ a
+ b
-c
-d
+ c
+ d
EOM
end
it "formats nested arrays with single- and empty subarrays appropriately" do
@ui.output([ %w{a b}, [ "c" ], [], %w{d e}])
- expect(@out.string).to eq <<EOM
-a
-b
+ expect(@out.string).to eq <<~EOM
+ a
+ b
-c
+ c
-d
-e
+ d
+ e
EOM
end
it "formats arrays of hashes with extra lines in between for readability" do
@ui.output([ { "a" => "b", "c" => "d" }, { "x" => "y" }, { "m" => "n", "o" => "p" }])
- expect(@out.string).to eq <<EOM
-a: b
-c: d
+ expect(@out.string).to eq <<~EOM
+ a: b
+ c: d
-x: y
+ x: y
-m: n
-o: p
+ m: n
+ o: p
EOM
end
it "formats hashes with empty array members appropriately" do
@ui.output({ "a" => [], "b" => "c" })
- expect(@out.string).to eq <<EOM
-a:
-b: c
+ expect(@out.string).to eq <<~EOM
+ a:
+ b: c
EOM
end
it "formats hashes with single-member array values appropriately" do
@ui.output({ "a" => [ "foo" ], "b" => "c" })
- expect(@out.string).to eq <<EOM
-a: foo
-b: c
+ expect(@out.string).to eq <<~EOM
+ a: foo
+ b: c
EOM
end
it "formats hashes with array members appropriately" do
@ui.output({ "a" => %w{foo bar}, "b" => "c" })
- expect(@out.string).to eq <<EOM
-a:
- foo
- bar
-b: c
+ expect(@out.string).to eq <<~EOM
+ a:
+ foo
+ bar
+ b: c
EOM
end
it "formats hashes with single-member nested array values appropriately" do
@ui.output({ "a" => [ [ "foo" ] ], "b" => "c" })
- expect(@out.string).to eq <<EOM
-a:
- foo
-b: c
+ expect(@out.string).to eq <<~EOM
+ a:
+ foo
+ b: c
EOM
end
@@ -327,19 +327,19 @@ EOM
it "formats hashes with hash values appropriately" do
@ui.output({ "a" => { "aa" => "bb", "cc" => "dd" }, "b" => "c" })
- expect(@out.string).to eq <<EOM
-a:
- aa: bb
- cc: dd
-b: c
+ expect(@out.string).to eq <<~EOM
+ a:
+ aa: bb
+ cc: dd
+ b: c
EOM
end
it "formats hashes with empty hash values appropriately" do
@ui.output({ "a" => {}, "b" => "c" })
- expect(@out.string).to eq <<EOM
-a:
-b: c
+ expect(@out.string).to eq <<~EOM
+ a:
+ b: c
EOM
end
end
@@ -358,7 +358,7 @@ EOM
describe "format_for_display" do
it "should return the raw data" do
- input = { :gi => :go }
+ input = { gi: :go }
expect(@ui.format_for_display(input)).to eq(input)
end
@@ -480,7 +480,7 @@ EOM
context "when running on Windows" do
before(:each) do
- stdout = double("StringIO", :tty? => true)
+ stdout = double("StringIO", tty?: true)
allow(@ui).to receive(:stdout).and_return(stdout)
allow(ChefConfig).to receive(:windows?) { true }
Chef::Config.reset
@@ -631,7 +631,7 @@ EOM
out = StringIO.new
allow(@ui).to receive(:stdout).and_return(out)
allow(@ui).to receive(:stdin).and_return(StringIO.new(" \n"))
- expect(@ui.ask_question("your chef server URL? ", :default => "http://localhost:4000")).to eq("http://localhost:4000")
+ expect(@ui.ask_question("your chef server URL? ", default: "http://localhost:4000")).to eq("http://localhost:4000")
expect(out.string).to eq("your chef server URL? [http://localhost:4000] ")
end
end
diff --git a/spec/unit/knife/data_bag_create_spec.rb b/spec/unit/knife/data_bag_create_spec.rb
index b7d185a58c..6624fb70ab 100644
--- a/spec/unit/knife/data_bag_create_spec.rb
+++ b/spec/unit/knife/data_bag_create_spec.rb
@@ -46,8 +46,8 @@ describe Chef::Knife::DataBagCreate do
allow(knife).to receive(:config).and_return(config)
end
- context "when data_bag already exist" do
- it "doesn't creates a data bag" do
+ context "when data_bag already exists" do
+ it "doesn't create a data bag" do
expect(knife).to receive(:create_object).and_yield(raw_hash)
expect(rest).to receive(:get).with("data/#{bag_name}")
expect(rest).to_not receive(:post).with("data", { "name" => bag_name })
@@ -60,7 +60,7 @@ describe Chef::Knife::DataBagCreate do
context "when data_bag doesn't exist" do
before do
# Data bag doesn't exist by default so we mock the GET request to return 404
- exception = double("404 error", :code => "404")
+ exception = double("404 error", code: "404")
allow(rest).to receive(:get)
.with("data/#{bag_name}")
.and_raise(Net::HTTPServerException.new("404", exception))
@@ -72,6 +72,35 @@ describe Chef::Knife::DataBagCreate do
expect { knife.run }.to exit_with_code(1)
end
+ it "won't create a data bag with a reserved name for search" do
+ %w{node role client environment}.each do |name|
+ knife.name_args = [name]
+ 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)
+ end
+ end
+
+ context "when part of the name is a reserved name" do
+ before do
+ exception = double("404 error", code: "404")
+ %w{node role client environment}.each do |name|
+ allow(rest).to receive(:get)
+ .with("data/sudoing_#{name}_admins")
+ .and_raise(Net::HTTPServerException.new("404", exception))
+ end
+ end
+
+ it "will create a data bag containing a reserved word" do
+ %w{node role client environment}.each do |name|
+ knife.name_args = ["sudoing_#{name}_admins"]
+ expect(rest).to receive(:post).with("data", { "name" => knife.name_args[0] })
+ expect(knife.ui).to receive(:info).with("Created data_bag[#{knife.name_args[0]}]")
+
+ knife.run
+ end
+ end
+ end
+
context "when given one argument" do
before do
knife.name_args = [bag_name]
@@ -85,6 +114,23 @@ describe Chef::Knife::DataBagCreate do
end
end
+ context "when given a data bag name partially matching a reserved name for search" do
+ %w{xnode rolex xenvironmentx xclientx}.each do |name|
+ let(:bag_name) { name }
+
+ before do
+ knife.name_args = [bag_name]
+ end
+
+ it "creates a data bag named '#{name}'" do
+ expect(rest).to receive(:post).with("data", { "name" => bag_name })
+ expect(knife.ui).to receive(:info).with("Created data_bag[#{bag_name}]")
+
+ knife.run
+ end
+ end
+ end
+
context "no secret is specified for encryption" do
let(:item) do
item = Chef::DataBagItem.from_hash(raw_hash)
diff --git a/spec/unit/knife/data_bag_edit_spec.rb b/spec/unit/knife/data_bag_edit_spec.rb
index 635dc63489..ff131a7d91 100644
--- a/spec/unit/knife/data_bag_edit_spec.rb
+++ b/spec/unit/knife/data_bag_edit_spec.rb
@@ -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
diff --git a/spec/unit/knife/data_bag_secret_options_spec.rb b/spec/unit/knife/data_bag_secret_options_spec.rb
index 2f4d8c8a88..5aa34029e9 100644
--- a/spec/unit/knife/data_bag_secret_options_spec.rb
+++ b/spec/unit/knife/data_bag_secret_options_spec.rb
@@ -73,13 +73,13 @@ describe Chef::Knife::DataBagSecretOptions do
it "returns the secret first" do
Chef::Config[:knife][:cl_secret] = secret
- expect(example_db).to receive(:config).and_return({ :secret => secret })
+ expect(example_db).to receive(:config).and_return({ secret: secret })
expect(example_db.read_secret).to eq(secret)
end
it "returns the secret_file only if secret does not exist" do
Chef::Config[:knife][:cl_secret_file] = secret_file.path
- expect(example_db).to receive(:config).and_return({ :secret_file => secret_file.path })
+ expect(example_db).to receive(:config).and_return({ secret_file: secret_file.path })
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
@@ -111,19 +111,19 @@ describe Chef::Knife::DataBagSecretOptions do
end
it "returns true if --encrypt is passed on the CL and :secret is in config" do
- expect(example_db).to receive(:config).and_return({ :encrypt => true })
+ expect(example_db).to receive(:config).and_return({ encrypt: true })
Chef::Config[:knife][:secret] = secret
expect(example_db.encryption_secret_provided?).to eq(true)
end
it "returns true if --encrypt is passed on the CL and :secret_file is in config" do
- expect(example_db).to receive(:config).and_return({ :encrypt => true })
+ expect(example_db).to receive(:config).and_return({ encrypt: true })
Chef::Config[:knife][:secret_file] = secret_file.path
expect(example_db.encryption_secret_provided?).to eq(true)
end
it "throws an error if --encrypt is passed and there is not :secret or :secret_file in the config" do
- expect(example_db).to receive(:config).and_return({ :encrypt => true })
+ expect(example_db).to receive(:config).and_return({ encrypt: true })
expect(example_db).to receive(:exit).with(1)
expect(example_db.ui).to receive(:fatal).with("No secret or secret_file specified in config, unable to encrypt item.")
example_db.encryption_secret_provided?
diff --git a/spec/unit/knife/data_bag_show_spec.rb b/spec/unit/knife/data_bag_show_spec.rb
index ece7f5bf78..8dd0669993 100644
--- a/spec/unit/knife/data_bag_show_spec.rb
+++ b/spec/unit/knife/data_bag_show_spec.rb
@@ -91,12 +91,11 @@ qux: http://localhost:4000/data/bag_o_data/qux}
context "Data bag to show is not encrypted" do
before do
allow(knife).to receive(:encrypted?).and_return(false)
- expect(knife).to receive(:read_secret).exactly(0).times
end
it "displays the data bag" do
+ expect(knife).to receive(:read_secret).exactly(0).times
expect(Chef::DataBagItem).to receive(:load).with(bag_name, item_name).and_return(data_bag)
- expect(knife.ui).to receive(:warn).with("Unencrypted data bag detected, ignoring any provided secret options.")
expected = %q{baz: http://localhost:4000/data/bag_o_data/baz
id: id
@@ -104,6 +103,21 @@ qux: http://localhost:4000/data/bag_o_data/qux}
knife.run
expect(stdout.string.strip).to eq(expected)
end
+
+ context "when a secret is given" do
+ it "displays the data bag" do
+ expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true)
+ expect(knife).to receive(:read_secret).and_return(secret)
+ expect(Chef::DataBagItem).to receive(:load).with(bag_name, item_name).and_return(data_bag)
+ expect(knife.ui).to receive(:warn).with("Unencrypted data bag detected, ignoring any provided secret options.")
+
+ expected = %q{baz: http://localhost:4000/data/bag_o_data/baz
+id: id
+qux: http://localhost:4000/data/bag_o_data/qux}
+ knife.run
+ expect(stdout.string.strip).to eq(expected)
+ end
+ end
end
it "displays the list of items in the data bag when only one @name_arg is provided" do
diff --git a/spec/unit/knife/environment_compare_spec.rb b/spec/unit/knife/environment_compare_spec.rb
index e408532884..82960f3db3 100644
--- a/spec/unit/knife/environment_compare_spec.rb
+++ b/spec/unit/knife/environment_compare_spec.rb
@@ -61,7 +61,7 @@ describe Chef::Knife::EnvironmentCompare do
it "should display only cookbooks with version constraints" do
@knife.config[:format] = "summary"
@knife.run
- @environments.each do |item, url|
+ @environments.each_key do |item|
expect(@stdout.string).to(match /#{item}/) && expect(@stdout.string.lines.count).to(be 4)
end
end
@@ -78,7 +78,7 @@ describe Chef::Knife::EnvironmentCompare do
@knife.config[:format] = "summary"
@knife.config[:mismatch] = true
@knife.run
- @constraints.each do |item, ver|
+ @constraints.each_value do |ver|
expect(@stdout.string).to match /#{ver[1]}/
end
end
@@ -96,7 +96,7 @@ describe Chef::Knife::EnvironmentCompare do
@knife.config[:format] = "summary"
@knife.config[:all] = true
@knife.run
- @constraints.each do |item, ver|
+ @constraints.each_value do |ver|
expect(@stdout.string).to match /#{ver[1]}/
end
end
diff --git a/spec/unit/knife/environment_from_file_spec.rb b/spec/unit/knife/environment_from_file_spec.rb
index 4505da3637..11e05cb922 100644
--- a/spec/unit/knife/environment_from_file_spec.rb
+++ b/spec/unit/knife/environment_from_file_spec.rb
@@ -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/index_rebuild_spec.rb b/spec/unit/knife/index_rebuild_spec.rb
deleted file mode 100644
index 97a3a69155..0000000000
--- a/spec/unit/knife/index_rebuild_spec.rb
+++ /dev/null
@@ -1,125 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2009-2016, Daniel DeLeo
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Knife::IndexRebuild do
-
- 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)
- end
-
- before :each do
- # This keeps the test output clean
- allow(knife.ui).to receive(:stdout).and_return(StringIO.new)
- end
-
- context "#grab_api_info" do
- let(:http_not_found_response) do
- e = Net::HTTPNotFound.new("1.1", 404, "blah")
- allow(e).to receive(:[]).with("x-ops-api-info").and_return(api_header_value)
- e
- end
-
- let(:http_server_exception) do
- Net::HTTPServerException.new("404: Not Found", http_not_found_response)
- end
-
- before(:each) do
- stub_rest!
- allow(rest_client).to receive(:get).and_raise(http_server_exception)
- end
-
- context "against a Chef 11 server" do
- 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" })
- end
- end # Chef 11
-
- context "against a Chef 10 server" do
- let(:api_header_value) { nil }
- it "finds no API information" do
- expect(knife.grab_api_info).to eq({})
- end
- end # Chef 10
- end # grab_api_info
-
- 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
- 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
- end
- end
-
- context "with Chef 10 API metadata" do
- it "is supported" do
- # Chef 10 will have no metadata
- expect(knife.unsupported_version?({})).to be_falsey
- end
- end
- 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!
- end
-
- context "against a Chef 11 server" do
- let(:api_info) do
- { "flavor" => "osc",
- "version" => "11.0.0",
- "erchef" => "1.2.3",
- }
- end
- let(:server_specific_stubs!) do
- expect(knife).to receive(:unsupported_server_message).with(api_info)
- expect(knife).to receive(:exit).with(1)
- end
-
- it "should not be allowed" do
- knife.run
- end
- end
-
- context "against a Chef 10 server" do
- let(:api_info) { {} }
- let(:server_specific_stubs!) do
- stub_rest!
- expect(rest_client).to receive(:post).with("/search/reindex", {}).and_return("representative output")
- expect(knife).not_to receive(:unsupported_server_message)
- expect(knife).to receive(:deprecated_server_message)
- expect(knife).to receive(:nag)
- expect(knife).to receive(:output).with("representative output")
- end
- it "should be allowed" do
- knife.run
- end
- end
- end
-
-end
diff --git a/spec/unit/knife/key_create_spec.rb b/spec/unit/knife/key_create_spec.rb
index 5b00c6ea31..fcbfd40381 100644
--- a/spec/unit/knife/key_create_spec.rb
+++ b/spec/unit/knife/key_create_spec.rb
@@ -44,9 +44,9 @@ describe "key create commands that inherit knife" do
context "when the service object is called" do
it "creates a new instance of Chef::Knife::KeyCreate with the correct args" do
- expect(Chef::Knife::KeyCreate).to receive(:new).
- with("charmander", command.actor_field_name, command.ui, command.config).
- and_return(service_object)
+ expect(Chef::Knife::KeyCreate).to receive(:new)
+ .with("charmander", command.actor_field_name, command.ui, command.config)
+ .and_return(service_object)
command.service_object
end
end # when the service object is called
@@ -207,7 +207,7 @@ Tfuc9dUYsFjptWYrV6pfEQ+bgo1OGBXORBFcFL+2D7u9JYquKrMgosznHoEkQNLo
end
end # when the server returns a private key
end # when the command is run
- end #key create run command"
+ end # key create run command"
context "when actor_field_name is 'user'" do
it_should_behave_like "key create run command" do
diff --git a/spec/unit/knife/key_delete_spec.rb b/spec/unit/knife/key_delete_spec.rb
index 0176f3c71e..87969198dc 100644
--- a/spec/unit/knife/key_delete_spec.rb
+++ b/spec/unit/knife/key_delete_spec.rb
@@ -44,9 +44,9 @@ 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)
+ expect(Chef::Knife::KeyDelete).to receive(:new)
+ .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
diff --git a/spec/unit/knife/key_edit_spec.rb b/spec/unit/knife/key_edit_spec.rb
index 244d8bdcc7..1650386da6 100644
--- a/spec/unit/knife/key_edit_spec.rb
+++ b/spec/unit/knife/key_edit_spec.rb
@@ -44,9 +44,9 @@ 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)
+ expect(Chef::Knife::KeyEdit).to receive(:new)
+ .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
diff --git a/spec/unit/knife/key_list_spec.rb b/spec/unit/knife/key_list_spec.rb
index 82fd1e4a09..e221a4da72 100644
--- a/spec/unit/knife/key_list_spec.rb
+++ b/spec/unit/knife/key_list_spec.rb
@@ -44,9 +44,9 @@ describe "key list commands that inherit knife" do
context "when the service object is called" do
it "creates a new instance of Chef::Knife::KeyList with the correct args" do
- expect(Chef::Knife::KeyList).to receive(:new).
- with("charmander", command.list_method, command.ui, command.config).
- and_return(service_object)
+ expect(Chef::Knife::KeyList).to receive(:new)
+ .with("charmander", command.list_method, command.ui, command.config)
+ .and_return(service_object)
command.service_object
end
end # when the service object is called
diff --git a/spec/unit/knife/key_show_spec.rb b/spec/unit/knife/key_show_spec.rb
index 139d4f91a2..f2eb244b23 100644
--- a/spec/unit/knife/key_show_spec.rb
+++ b/spec/unit/knife/key_show_spec.rb
@@ -44,9 +44,9 @@ 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)
+ expect(Chef::Knife::KeyShow).to receive(:new)
+ .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/knife_help.rb b/spec/unit/knife/knife_help.rb
deleted file mode 100644
index 0369951511..0000000000
--- a/spec/unit/knife/knife_help.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-#
-# Author:: Bryan McLellan <btm@loftninjas.org>
-# Copyright:: Copyright 2011-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Knife::Help do
- before(:each) do
- # Perilously use the build in list even though it is dynamic so we don't get warnings about the constant
- # HELP_TOPICS = [ "foo", "bar", "knife-kittens", "ceiling-cat", "shell" ]
- @knife = Chef::Knife::Help.new
- end
-
- it "should return a list of help topics" do
- expect(@knife.help_topics).to include("knife-status")
- end
-
- it "should run man for you" do
- @knife.name_args = [ "shell" ]
- expect(@knife).to receive(:exec).with(/^man \/.*\/shell.1$/)
- @knife.run
- end
-
- it "should suggest topics" do
- @knife.name_args = [ "list" ]
- allow(@knife.ui).to receive(:msg)
- expect(@knife.ui).to receive(:info).with("Available help topics are: ")
- expect(@knife.ui).to receive(:msg).with(/knife/)
- allow(@knife).to receive(:exec)
- expect(@knife).to receive(:exit).with(1)
- @knife.run
- end
-
- describe "find_manpage_path" do
- it "should find the man page in the gem" do
- expect(@knife.find_manpage_path("shell")).to match(/distro\/common\/man\/man1\/chef-shell.1$/)
- end
-
- it "should provide the man page name if not in the gem" do
- expect(@knife.find_manpage_path("foo")).to eq("foo")
- end
- end
-
- describe "find_manpages_for_query" do
- it "should error if it does not find a match" do
- allow(@knife.ui).to receive(:error)
- allow(@knife.ui).to receive(:info)
- allow(@knife.ui).to receive(:msg)
- expect(@knife).to receive(:exit).with(1)
- expect(@knife.ui).to receive(:error).with("No help found for 'chickens'")
- expect(@knife.ui).to receive(:msg).with(/knife/)
- @knife.find_manpages_for_query("chickens")
- end
- end
-
- describe "print_help_topics" do
- it "should print the known help topics" do
- allow(@knife.ui).to receive(:msg)
- allow(@knife.ui).to receive(:info)
- expect(@knife.ui).to receive(:msg).with(/knife/)
- @knife.print_help_topics
- end
-
- it "should shorten topics prefixed by knife-" do
- allow(@knife.ui).to receive(:msg)
- allow(@knife.ui).to receive(:info)
- expect(@knife.ui).to receive(:msg).with(/node/)
- @knife.print_help_topics
- end
-
- it "should not leave topics prefixed by knife-" do
- allow(@knife.ui).to receive(:msg)
- allow(@knife.ui).to receive(:info)
- expect(@knife.ui).not_to receive(:msg).with(/knife-node/)
- @knife.print_help_topics
- end
- end
-end
diff --git a/spec/unit/knife/node_delete_spec.rb b/spec/unit/knife/node_delete_spec.rb
index 1a6b277dbb..cc2e0b23af 100644
--- a/spec/unit/knife/node_delete_spec.rb
+++ b/spec/unit/knife/node_delete_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::NodeDelete do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::NodeDelete.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = %w{ adam ben }
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/node_edit_spec.rb b/spec/unit/knife/node_edit_spec.rb
index dedb5c949d..dfc0986ebe 100644
--- a/spec/unit/knife/node_edit_spec.rb
+++ b/spec/unit/knife/node_edit_spec.rb
@@ -23,16 +23,16 @@ 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)))
+ 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"
@knife = Chef::Knife::NodeEdit.new
@knife.config = {
- :editor => "cat",
- :attribute => nil,
- :print_after => nil,
+ editor: "cat",
+ attribute: nil,
+ print_after: nil,
}
@knife.name_args = [ "adam" ]
@node = Chef::Node.new()
@@ -45,11 +45,13 @@ describe Chef::Knife::NodeEdit do
describe "after loading the node" do
before do
+ @knife.config[:all_attributes] = false
+
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
diff --git a/spec/unit/knife/node_from_file_spec.rb b/spec/unit/knife/node_from_file_spec.rb
index 61c63c150e..cf128a80a0 100644
--- a/spec/unit/knife/node_from_file_spec.rb
+++ b/spec/unit/knife/node_from_file_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::NodeFromFile do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::NodeFromFile.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "adam.rb" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/node_policy_set_spec.rb b/spec/unit/knife/node_policy_set_spec.rb
new file mode 100644
index 0000000000..35306937d8
--- /dev/null
+++ b/spec/unit/knife/node_policy_set_spec.rb
@@ -0,0 +1,122 @@
+#
+# Author:: Piyush Awasthi (<piyush.awasthi@chef.io>)
+# Copyright:: Copyright 2017-2018, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Knife::NodePolicySet do
+ let(:node) do
+ node = Chef::Node.new()
+ node.name("adam")
+ node.run_list = ["role[base]"]
+ node
+ end
+
+ let(:knife) do
+ Chef::Log.logger = Logger.new(StringIO.new)
+ Chef::Config[:knife][:bootstrap_template] = bootstrap_template unless bootstrap_template.nil?
+ knife_obj = Chef::Knife::NodePolicySet.new(bootstrap_cli_options)
+ knife_obj.merge_configs
+ allow(knife_obj.ui).to receive(:stderr).and_return(stderr)
+ allow(knife_obj).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(false)
+ knife_obj
+ end
+
+ let(:stderr) { StringIO.new }
+ let(:bootstrap_template) { nil }
+ let(:bootstrap_cli_options) { [ ] }
+
+ describe "#run" do
+ context "when node_name is not given" do
+ let(:bootstrap_cli_options) { %w{ } }
+ it "returns an error that you must specify a node name" do
+ expect { knife.send(:validate_node!) }.to raise_error(SystemExit)
+ expect(stderr.string).to include("ERROR: You must specify a node name")
+ end
+ end
+
+ context "when node is given" do
+ let(:bootstrap_cli_options) { %w{ adam staging my-app } }
+ it "should load the node" do
+ expect(Chef::Node).to receive(:load).with(bootstrap_cli_options[0]).and_return(node)
+ allow(node).to receive(:save).and_return(true)
+ knife.run
+ end
+ end
+
+ context "when node not saved" do
+ let(:bootstrap_cli_options) { %w{ adam staging my-app } }
+ it "returns an error node not updated successfully" do
+ allow(Chef::Node).to receive(:load).with(bootstrap_cli_options[0]).and_return(node)
+ allow(node).to receive(:save).and_return(false)
+ knife.run
+ expect(stderr.string.strip).to eq("Error in updating node #{node.name}")
+ end
+ end
+
+ context "when the policy is set successfully on the node" do
+ let(:bootstrap_cli_options) { %w{ adam staging my-app } }
+ it "returns node updated successfully" do
+ allow(Chef::Node).to receive(:load).with(bootstrap_cli_options[0]).and_return(node)
+ allow(node).to receive(:save).and_return(true)
+ knife.run
+ expect(stderr.string.strip).to eq("Successfully set the policy on node #{node.name}")
+ end
+ end
+ end
+
+ describe "handling policy options" do
+ context "when policy_group and policy_name is not given" do
+ let(:bootstrap_cli_options) { %w{ } }
+ it "returns an error stating that policy_name and policy_group must be given together" do
+ expect { knife.send(:validate_options!) }.to raise_error(SystemExit)
+ expect(stderr.string).to include("ERROR: Policy group and name must be specified together")
+ end
+ end
+
+ context "when only policy_name is given" do
+ let(:bootstrap_cli_options) { %w{ adam staging } }
+ it "returns an error stating that policy_name and policy_group must be given together" do
+ expect { knife.send(:validate_options!) }.to raise_error(SystemExit)
+ expect(stderr.string).to include("ERROR: Policy group and name must be specified together")
+ end
+ end
+
+ context "when only policy_group is given" do
+ let(:bootstrap_cli_options) { %w{ adam my-app } }
+ it "returns an error stating that policy_name and policy_group must be given together" do
+ expect { knife.send(:validate_options!) }.to raise_error(SystemExit)
+ expect(stderr.string).to include("ERROR: Policy group and name must be specified together")
+ end
+ end
+
+ context "when policy_name and policy_group are given with no conflicting options" do
+ let(:bootstrap_cli_options) { %w{ adam staging my-app } }
+ it "passes options validation" do
+ expect { knife.send(:validate_options!) }.to_not raise_error
+ end
+
+ it "returns value set in config" do
+ allow(Chef::Node).to receive(:load).with(bootstrap_cli_options[0]).and_return(node)
+ allow(node).to receive(:save).and_return(false)
+ knife.run
+ expect(node.policy_name).to eq("my-app")
+ expect(node.policy_group).to eq("staging")
+ end
+ 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 e11bf78029..03c89ff9eb 100644
--- a/spec/unit/knife/node_run_list_add_spec.rb
+++ b/spec/unit/knife/node_run_list_add_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::NodeRunListAdd do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::NodeRunListAdd.new
@knife.config = {
- :after => nil,
+ after: nil,
}
@knife.name_args = [ "adam", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/osc_user_edit_spec.rb b/spec/unit/knife/osc_user_edit_spec.rb
index 59fb152b5b..1792e38027 100644
--- a/spec/unit/knife/osc_user_edit_spec.rb
+++ b/spec/unit/knife/osc_user_edit_spec.rb
@@ -37,7 +37,7 @@ describe Chef::Knife::OscUserEdit do
end
it "loads and edits the user" do
- data = { :name => "my_user" }
+ data = { name: "my_user" }
allow(Chef::User).to receive(:load).with("my_user").and_return(data)
expect(@knife).to receive(:edit_hash).with(data).and_return(data)
@knife.run
diff --git a/spec/unit/knife/osc_user_reregister_spec.rb b/spec/unit/knife/osc_user_reregister_spec.rb
index ae6b4be9a8..b0ac92568e 100644
--- a/spec/unit/knife/osc_user_reregister_spec.rb
+++ b/spec/unit/knife/osc_user_reregister_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
# DEPRECATION NOTE
-# This code only remains to support users still operating with
+# This code only remains to support users still operating with
# Open Source Chef Server 11 and should be removed once support
# for OSC 11 ends. New development should occur in user_reregister_spec.rb.
@@ -28,7 +28,7 @@ describe Chef::Knife::OscUserReregister do
Chef::Knife::OscUserReregister.load_deps
@knife = Chef::Knife::OscUserReregister.new
@knife.name_args = [ "a_user" ]
- @user_mock = double("user_mock", :private_key => "private_key")
+ @user_mock = double("user_mock", private_key: "private_key")
allow(Chef::User).to receive(:load).and_return(@user_mock)
@stdout = StringIO.new
allow(@knife.ui).to receive(:stdout).and_return(@stdout)
diff --git a/spec/unit/knife/osc_user_show_spec.rb b/spec/unit/knife/osc_user_show_spec.rb
index d6efbef870..ecdb0a9fce 100644
--- a/spec/unit/knife/osc_user_show_spec.rb
+++ b/spec/unit/knife/osc_user_show_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
# DEPRECATION NOTE
-# This code only remains to support users still operating with
+# This code only remains to support users still operating with
# Open Source Chef Server 11 and should be removed once support
# for OSC 11 ends. New development should occur user_show_spec.rb.
diff --git a/spec/unit/knife/role_bulk_delete_spec.rb b/spec/unit/knife/role_bulk_delete_spec.rb
index e9054c1d00..d49adb9354 100644
--- a/spec/unit/knife/role_bulk_delete_spec.rb
+++ b/spec/unit/knife/role_bulk_delete_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::RoleBulkDelete do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::RoleBulkDelete.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = ["."]
@stdout = StringIO.new
diff --git a/spec/unit/knife/role_create_spec.rb b/spec/unit/knife/role_create_spec.rb
index 9466d9642c..5e2b2caeb5 100644
--- a/spec/unit/knife/role_create_spec.rb
+++ b/spec/unit/knife/role_create_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::RoleCreate do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::RoleCreate.new
@knife.config = {
- :description => nil,
+ description: nil,
}
@knife.name_args = [ "adam" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_delete_spec.rb b/spec/unit/knife/role_delete_spec.rb
index f095e5ba2d..98c0cde9b2 100644
--- a/spec/unit/knife/role_delete_spec.rb
+++ b/spec/unit/knife/role_delete_spec.rb
@@ -23,7 +23,7 @@ describe Chef::Knife::RoleDelete do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::RoleDelete.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "adam" ]
allow(@knife).to receive(:output).and_return(true)
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 4738101f90..242beeb4a2 100644
--- a/spec/unit/knife/role_env_run_list_add_spec.rb
+++ b/spec/unit/knife/role_env_run_list_add_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::RoleEnvRunListAdd do
# Chef::Config[:env_name] = "QA"
@knife = Chef::Knife::RoleEnvRunListAdd.new
@knife.config = {
- :after => nil,
+ after: nil,
}
@knife.name_args = [ "will", "QA", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
@@ -85,17 +85,17 @@ describe Chef::Knife::RoleEnvRunListAdd do
end
it "should add to the run list after the specified entries in the QA run list" do
- #Setup
+ # Setup
@role.run_list_for("_default") << "role[acorns]"
@role.run_list_for("_default") << "role[barn]"
@knife.run
@role.run_list_for("QA") << "role[pencil]"
@role.run_list_for("QA") << "role[pen]"
- #Configuration we are testing
+ # Configuration we are testing
@knife.config[:after] = "role[pencil]"
@knife.name_args = [ "will", "QA", "role[pad]", "role[whackadoo]" ]
@knife.run
- #The actual tests
+ # The actual tests
expect(@role.run_list_for("QA")[0]).to eq("role[monkey]")
expect(@role.run_list_for("QA")[1]).to eq("role[pencil]")
expect(@role.run_list_for("QA")[2]).to eq("role[pad]")
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 c9c24858c0..7a580ecd4a 100644
--- a/spec/unit/knife/role_env_run_list_clear_spec.rb
+++ b/spec/unit/knife/role_env_run_list_clear_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::RoleEnvRunListClear do
@knife = Chef::Knife::RoleEnvRunListClear.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = %w{will QA}
allow(@knife).to receive(:output).and_return(true)
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 8a077f1de3..afbabec528 100644
--- a/spec/unit/knife/role_env_run_list_remove_spec.rb
+++ b/spec/unit/knife/role_env_run_list_remove_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::RoleEnvRunListRemove do
@knife = Chef::Knife::RoleEnvRunListRemove.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "QA", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
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 08dcdd90e2..c4d231d638 100644
--- a/spec/unit/knife/role_env_run_list_replace_spec.rb
+++ b/spec/unit/knife/role_env_run_list_replace_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::RoleEnvRunListReplace do
@knife = Chef::Knife::RoleEnvRunListReplace.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "QA", "role[dude]", "role[person]" ]
allow(@knife).to receive(:output).and_return(true)
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 aed1c9fe1e..79bd3b152e 100644
--- a/spec/unit/knife/role_env_run_list_set_spec.rb
+++ b/spec/unit/knife/role_env_run_list_set_spec.rb
@@ -28,7 +28,7 @@ describe Chef::Knife::RoleEnvRunListSet do
@knife = Chef::Knife::RoleEnvRunListSet.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "QA", "role[owen]", "role[mauntel]" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_from_file_spec.rb b/spec/unit/knife/role_from_file_spec.rb
index 104894df17..827b8ae04d 100644
--- a/spec/unit/knife/role_from_file_spec.rb
+++ b/spec/unit/knife/role_from_file_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::RoleFromFile do
Chef::Config[:node_name] = "webmonkey.example.com"
@knife = Chef::Knife::RoleFromFile.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "adam.rb" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_run_list_add_spec.rb b/spec/unit/knife/role_run_list_add_spec.rb
index fe7318c040..a38b6de9da 100644
--- a/spec/unit/knife/role_run_list_add_spec.rb
+++ b/spec/unit/knife/role_run_list_add_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Knife::RoleRunListAdd do
# Chef::Config[:env_name] = "QA"
@knife = Chef::Knife::RoleRunListAdd.new
@knife.config = {
- :after => nil,
+ after: nil,
}
@knife.name_args = [ "will", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
@@ -74,14 +74,14 @@ describe Chef::Knife::RoleRunListAdd do
end
it "should add to the run list after the specified entries in the default run list" do
- #Setup
+ # Setup
@role.run_list_for("_default") << "role[acorns]"
@role.run_list_for("_default") << "role[barn]"
- #Configuration we are testing
+ # Configuration we are testing
@knife.config[:after] = "role[acorns]"
@knife.name_args = [ "will", "role[pad]", "role[whackadoo]" ]
@knife.run
- #The actual tests
+ # The actual tests
expect(@role.run_list[0]).to eq("role[acorns]")
expect(@role.run_list[1]).to eq("role[pad]")
expect(@role.run_list[2]).to eq("role[whackadoo]")
diff --git a/spec/unit/knife/role_run_list_clear_spec.rb b/spec/unit/knife/role_run_list_clear_spec.rb
index 4ed1f312b0..8bbc816d6f 100644
--- a/spec/unit/knife/role_run_list_clear_spec.rb
+++ b/spec/unit/knife/role_run_list_clear_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::RoleRunListClear do
@knife = Chef::Knife::RoleRunListClear.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_run_list_remove_spec.rb b/spec/unit/knife/role_run_list_remove_spec.rb
index 087bc2c6ee..c18416feca 100644
--- a/spec/unit/knife/role_run_list_remove_spec.rb
+++ b/spec/unit/knife/role_run_list_remove_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::RoleRunListRemove do
@knife = Chef::Knife::RoleRunListRemove.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "role[monkey]" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_run_list_replace_spec.rb b/spec/unit/knife/role_run_list_replace_spec.rb
index 2bc060ae2d..9b212de0ae 100644
--- a/spec/unit/knife/role_run_list_replace_spec.rb
+++ b/spec/unit/knife/role_run_list_replace_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::RoleRunListReplace do
@knife = Chef::Knife::RoleRunListReplace.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "role[dude]", "role[person]" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/role_run_list_set_spec.rb b/spec/unit/knife/role_run_list_set_spec.rb
index 27b4d9fea1..f8e440f524 100644
--- a/spec/unit/knife/role_run_list_set_spec.rb
+++ b/spec/unit/knife/role_run_list_set_spec.rb
@@ -27,7 +27,7 @@ describe Chef::Knife::RoleRunListSet do
@knife = Chef::Knife::RoleRunListSet.new
@knife.config = {
- :print_after => nil,
+ print_after: nil,
}
@knife.name_args = [ "will", "role[owen]", "role[mauntel]" ]
allow(@knife).to receive(:output).and_return(true)
diff --git a/spec/unit/knife/ssh_spec.rb b/spec/unit/knife/ssh_spec.rb
index e15ca8a7f0..9cefcba84f 100644
--- a/spec/unit/knife/ssh_spec.rb
+++ b/spec/unit/knife/ssh_spec.rb
@@ -49,28 +49,36 @@ describe Chef::Knife::Ssh do
def self.should_return_specified_attributes
it "returns an array of the attributes specified on the command line OR config file, if only one is set" do
- @node_bar["config"] = "10.0.0.2"
- @node_foo["config"] = "10.0.0.1"
- @knife.config[:attribute] = "ipaddress"
+ @node_bar["target"] = "10.0.0.2"
+ @node_foo["target"] = "10.0.0.1"
+ @node_bar["prefix"] = "bar"
+ @node_foo["prefix"] = "foo"
+ @knife.config[:ssh_attribute] = "ipaddress"
+ @knife.config[:prefix_attribute] = "name"
Chef::Config[:knife][:ssh_attribute] = "ipaddress" # this value will be in the config file
- expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil], ["10.0.0.2", nil]])
+ Chef::Config[:knife][:prefix_attribute] = "name" # this value will be in the config file
+ expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil, "foo"], ["10.0.0.2", nil, "bar"]])
@knife.configure_session
end
it "returns an array of the attributes specified on the command line even when a config value is set" do
- @node_bar["config"] = "10.0.0.2"
- @node_foo["config"] = "10.0.0.1"
+ @node_bar["target"] = "10.0.0.2"
+ @node_foo["target"] = "10.0.0.1"
+ @node_bar["prefix"] = "bar"
+ @node_foo["prefix"] = "foo"
Chef::Config[:knife][:ssh_attribute] = "config_file" # this value will be in the config file
- @knife.config[:attribute] = "ipaddress" # this is the value of the command line via #configure_attribute
- expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil], ["10.0.0.2", nil]])
+ Chef::Config[:knife][:prefix_attribute] = "config_file" # this value will be in the config file
+ @knife.config[:ssh_attribute] = "ipaddress" # this is the value of the command line via #configure_attribute
+ @knife.config[:prefix_attribute] = "name" # this is the value of the command line via #configure_attribute
+ expect(@knife).to receive(:session_from_list).with([["10.0.0.1", nil, "foo"], ["10.0.0.2", nil, "bar"]])
@knife.configure_session
end
end
- it "searchs for and returns an array of fqdns" do
+ it "searches for and returns an array of fqdns" do
expect(@knife).to receive(:session_from_list).with([
- ["foo.example.org", nil],
- ["bar.example.org", nil],
+ ["foo.example.org", nil, nil],
+ ["bar.example.org", nil, nil],
])
@knife.configure_session
end
@@ -84,8 +92,8 @@ describe Chef::Knife::Ssh do
end
it "returns an array of cloud public hostnames" do
expect(@knife).to receive(:session_from_list).with([
- ["ec2-10-0-0-1.compute-1.amazonaws.com", nil],
- ["ec2-10-0-0-2.compute-1.amazonaws.com", nil],
+ ["ec2-10-0-0-1.compute-1.amazonaws.com", nil, nil],
+ ["ec2-10-0-0-2.compute-1.amazonaws.com", nil, nil],
])
@knife.configure_session
end
@@ -101,8 +109,8 @@ describe Chef::Knife::Ssh do
it "returns an array of fqdns" do
expect(@knife).to receive(:session_from_list).with([
- ["foo.example.org", nil],
- ["bar.example.org", nil],
+ ["foo.example.org", nil, nil],
+ ["bar.example.org", nil, nil],
])
@knife.configure_session
end
@@ -129,6 +137,24 @@ describe Chef::Knife::Ssh do
@knife.configure_session
end
end
+
+ context "when there are some hosts found but IPs duplicated if duplicated_fqdns option sets :fatal" do
+ before do
+ @knife.config[:duplicated_fqdns] = :fatal
+ @node_foo["fqdn"] = "foo.example.org"
+ @node_bar["fqdn"] = "foo.example.org"
+ end
+
+ it "should raise a specific error" do
+ expect(@knife.ui).to receive(:fatal).with(/^SSH node is duplicated: foo\.example\.org/)
+ expect(@knife).to receive(:exit).with(10)
+ expect(@knife).to receive(:session_from_list).with([
+ ["foo.example.org", nil, nil],
+ ["foo.example.org", nil, nil],
+ ])
+ @knife.configure_session
+ end
+ end
end
context "manual is set to true" do
@@ -144,15 +170,35 @@ describe Chef::Knife::Ssh do
end
end
+ describe "#get_prefix_attribute" do
+ # Order of precedence for prefix
+ # 1) config value (cli or knife config)
+ # 2) nil
+ before do
+ Chef::Config[:knife][:prefix_attribute] = nil
+ @knife.config[:prefix_attribute] = nil
+ @node_foo["cloud"]["public_hostname"] = "ec2-10-0-0-1.compute-1.amazonaws.com"
+ @node_bar["cloud"]["public_hostname"] = ""
+ end
+
+ it "should return nil by default" do
+ expect(@knife.get_prefix_attribute({})).to eq(nil)
+ end
+
+ it "should favor config over nil" do
+ @node_foo["prefix"] = "config"
+ expect( @knife.get_prefix_attribute(@node_foo)).to eq("config")
+ end
+ end
+
describe "#get_ssh_attribute" do
# Order of precedence for ssh target
- # 1) command line attribute
- # 2) configuration file
- # 3) cloud attribute
- # 4) fqdn
+ # 1) config value (cli or knife config)
+ # 2) cloud attribute
+ # 3) fqdn
before do
Chef::Config[:knife][:ssh_attribute] = nil
- @knife.config[:attribute] = nil
+ @knife.config[:ssh_attribute] = nil
@node_foo["cloud"]["public_hostname"] = "ec2-10-0-0-1.compute-1.amazonaws.com"
@node_bar["cloud"]["public_hostname"] = ""
end
@@ -165,18 +211,9 @@ describe Chef::Knife::Ssh do
expect(@knife.get_ssh_attribute(@node_foo)).to eq("ec2-10-0-0-1.compute-1.amazonaws.com")
end
- 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"
- @node_foo["config"] = "command_line"
- @node_foo["knife_config"] = "config_file"
- expect( @knife.get_ssh_attribute(@node_foo)).to eq("command_line")
- end
-
- it "should favor config file over cloud and default" do
- Chef::Config[:knife][:ssh_attribute] = "config_file"
- @node_foo["knife_config"] = "config_file"
- expect( @knife.get_ssh_attribute(@node_foo)).to eq("config_file")
+ it "should favor config over cloud and default" do
+ @node_foo["target"] = "config"
+ expect( @knife.get_ssh_attribute(@node_foo)).to eq("config")
end
it "should return fqdn if cloud.hostname is empty" do
@@ -187,84 +224,94 @@ describe Chef::Knife::Ssh do
describe "#session_from_list" do
before :each do
@knife.instance_variable_set(:@longest, 0)
- ssh_config = { :timeout => 50, :user => "locutus", :port => 23, :keepalive => true, :keepalive_interval => 60 }
+ ssh_config = { timeout: 50, user: "locutus", port: 23, keepalive: true, keepalive_interval: 60 }
allow(Net::SSH).to receive(:configuration_for).with("the.b.org", true).and_return(ssh_config)
end
it "uses the port from an ssh config file" do
- @knife.session_from_list([["the.b.org", nil]])
+ @knife.session_from_list([["the.b.org", nil, nil]])
expect(@knife.session.servers[0].port).to eq(23)
end
it "uses the port from a cloud attr" do
- @knife.session_from_list([["the.b.org", 123]])
+ @knife.session_from_list([["the.b.org", 123, nil]])
expect(@knife.session.servers[0].port).to eq(123)
end
+ it "uses the prefix from list" do
+ @knife.session_from_list([["the.b.org", nil, "b-team"]])
+ expect(@knife.session.servers[0][:prefix]).to eq("b-team")
+ end
+
+ it "defaults to a prefix of host" do
+ @knife.session_from_list([["the.b.org", nil, nil]])
+ expect(@knife.session.servers[0][:prefix]).to eq("the.b.org")
+ end
+
it "defaults to a timeout of 120 seconds" do
- @knife.session_from_list([["the.b.org", nil]])
+ @knife.session_from_list([["the.b.org", nil, nil]])
expect(@knife.session.servers[0].options[:timeout]).to eq(120)
end
it "uses the timeout from Chef Config" do
Chef::Config[:knife][:ssh_timeout] = 5
@knife.config[:ssh_timeout] = nil
- @knife.session_from_list([["the.b.org", nil]])
+ @knife.session_from_list([["the.b.org", nil, nil]])
expect(@knife.session.servers[0].options[:timeout]).to eq(5)
end
it "uses the timeout from knife config" do
@knife.config[:ssh_timeout] = 6
- @knife.session_from_list([["the.b.org", nil]])
+ @knife.session_from_list([["the.b.org", nil, nil]])
expect(@knife.session.servers[0].options[:timeout]).to eq(6)
end
it "uses the user from an ssh config file" do
- @knife.session_from_list([["the.b.org", 123]])
+ @knife.session_from_list([["the.b.org", 123, nil]])
expect(@knife.session.servers[0].user).to eq("locutus")
end
it "uses keepalive settings from an ssh config file" do
- @knife.session_from_list([["the.b.org", 123]])
+ @knife.session_from_list([["the.b.org", 123, nil]])
expect(@knife.session.servers[0].options[:keepalive]).to be true
expect(@knife.session.servers[0].options[:keepalive_interval]).to eq 60
end
end
describe "#ssh_command" do
- let(:execution_channel) { double(:execution_channel, :on_data => nil) }
- let(:session_channel) { double(:session_channel, :request_pty => nil) }
+ let(:execution_channel) { double(:execution_channel, on_data: 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(:execution_channel2) { double(:execution_channel, on_data: nil) }
+ let(:session_channel2) { double(:session_channel, request_pty: nil) }
- let(:session) { double(:session, :loop => nil) }
+ let(:session) { double(:session, loop: nil) }
let(:command) { "false" }
before do
- expect(execution_channel).
- to receive(:on_request).
- and_yield(nil, double(:data_stream, :read_long => exit_status))
-
- expect(session_channel).
- to receive(:exec).
- with(command).
- and_yield(execution_channel, true)
-
- expect(execution_channel2).
- to receive(:on_request).
- and_yield(nil, double(:data_stream, :read_long => exit_status2))
-
- expect(session_channel2).
- to receive(:exec).
- with(command).
- and_yield(execution_channel2, true)
-
- expect(session).
- to receive(:open_channel).
- and_yield(session_channel).
- and_yield(session_channel2)
+ expect(execution_channel)
+ .to receive(:on_request)
+ .and_yield(nil, double(:data_stream, read_long: exit_status))
+
+ expect(session_channel)
+ .to receive(:exec)
+ .with(command)
+ .and_yield(execution_channel, true)
+
+ expect(execution_channel2)
+ .to receive(:on_request)
+ .and_yield(nil, double(:data_stream, read_long: exit_status2))
+
+ expect(session_channel2)
+ .to receive(:exec)
+ .with(command)
+ .and_yield(execution_channel2, true)
+
+ expect(session)
+ .to receive(:open_channel)
+ .and_yield(session_channel)
+ .and_yield(session_channel2)
end
context "both connections return 0" do
@@ -295,6 +342,23 @@ describe Chef::Knife::Ssh do
end
end
+ describe "#tmux" do
+ before do
+ ssh_config = { timeout: 50, user: "locutus", port: 23, keepalive: true, keepalive_interval: 60 }
+ allow(Net::SSH).to receive(:configuration_for).with("foo.example.org", true).and_return(ssh_config)
+ @query = Chef::Search::Query.new
+ expect(@query).to receive(:search).and_yield(@node_foo)
+ allow(Chef::Search::Query).to receive(:new).and_return(@query)
+ allow(@knife).to receive(:exec).and_return(0)
+ end
+
+ it "filters out invalid characters from tmux session name" do
+ @knife.name_args = ["name:foo.example.org", "tmux"]
+ expect(@knife).to receive(:shell_out!).with("tmux new-session -d -s 'knife ssh name=foo-example-org' -n 'foo.example.org' 'ssh locutus@foo.example.org' ")
+ @knife.run
+ end
+ end
+
describe "#run" do
before do
@query = Chef::Search::Query.new
diff --git a/spec/unit/knife/ssl_check_spec.rb b/spec/unit/knife/ssl_check_spec.rb
index 8aa18c3abc..9092110b95 100644
--- a/spec/unit/knife/ssl_check_spec.rb
+++ b/spec/unit/knife/ssl_check_spec.rb
@@ -67,11 +67,11 @@ describe Chef::Knife::SslCheck do
it "prints an error and exits" do
expect { ssl_check.run }.to raise_error(SystemExit)
- expected_stdout = <<-E
-USAGE: knife ssl check [URL] (options)
+ expected_stdout = <<~E
+ USAGE: knife ssl check [URL] (options)
E
- expected_stderr = <<-E
-ERROR: Given URI: `foo.test' is invalid
+ expected_stderr = <<~E
+ ERROR: Given URI: `foo.test' is invalid
E
expect(stdout_io.string).to eq(expected_stdout)
expect(stderr_io.string).to eq(expected_stderr)
@@ -83,11 +83,11 @@ E
it "prints an error and exits" do
expect { ssl_check.run }.to raise_error(SystemExit)
- expected_stdout = <<-E
-USAGE: knife ssl check [URL] (options)
+ expected_stdout = <<~E
+ USAGE: knife ssl check [URL] (options)
E
- expected_stderr = <<-E
-ERROR: Given URI: `#{name_args[0]}' is invalid
+ expected_stderr = <<~E
+ ERROR: Given URI: `#{name_args[0]}' is invalid
E
expect(stdout_io.string).to eq(expected_stdout)
expect(stderr_io.string).to eq(expected_stderr)
@@ -168,8 +168,8 @@ E
def run
ssl_check.run
rescue Exception
- #puts "OUT: #{stdout_io.string}"
- #puts "ERR: #{stderr_io.string}"
+ # puts "OUT: #{stdout_io.string}"
+ # puts "ERR: #{stderr_io.string}"
raise
end
@@ -199,12 +199,12 @@ E
before do
@old_signal = trap(:INT, "DEFAULT")
- expect(ssl_check).to receive(:proxified_socket).
- with("foo.example.com", 8443).
- and_return(tcp_socket_for_debug)
- expect(OpenSSL::SSL::SSLSocket).to receive(:new).
- with(tcp_socket_for_debug, ssl_check.noverify_peer_ssl_context).
- and_return(ssl_socket_for_debug)
+ expect(ssl_check).to receive(:proxified_socket)
+ .with("foo.example.com", 8443)
+ .and_return(tcp_socket_for_debug)
+ expect(OpenSSL::SSL::SSLSocket).to receive(:new)
+ .with(tcp_socket_for_debug, ssl_check.noverify_peer_ssl_context)
+ .and_return(ssl_socket_for_debug)
end
after do
@@ -215,9 +215,9 @@ E
before do
expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs
expect(ssl_socket).to receive(:connect) # no error
- expect(ssl_socket).to receive(:post_connection_check).
- with("foo.example.com").
- and_raise(OpenSSL::SSL::SSLError)
+ expect(ssl_socket).to receive(:post_connection_check)
+ .with("foo.example.com")
+ .and_raise(OpenSSL::SSL::SSLError)
expect(ssl_socket).to receive(:hostname=).with("foo.example.com") # no error
expect(ssl_socket_for_debug).to receive(:connect)
expect(ssl_socket_for_debug).to receive(:peer_cert).and_return(self_signed_crt)
@@ -235,10 +235,10 @@ E
context "when the cert is not signed by any trusted authority" do
before do
expect(ssl_check).to receive(:verify_X509).and_return(true) # X509 valid certs
- expect(ssl_socket).to receive(:connect).
- and_raise(OpenSSL::SSL::SSLError)
- expect(ssl_socket).to receive(:hostname=).
- with("foo.example.com") # no error
+ expect(ssl_socket).to receive(:connect)
+ .and_raise(OpenSSL::SSL::SSLError)
+ expect(ssl_socket).to receive(:hostname=)
+ .with("foo.example.com") # no error
expect(ssl_socket_for_debug).to receive(:connect)
expect(ssl_socket_for_debug).to receive(:peer_cert).and_return(self_signed_crt)
end
diff --git a/spec/unit/knife/ssl_fetch_spec.rb b/spec/unit/knife/ssl_fetch_spec.rb
index bc49c40241..45dd27ceec 100644
--- a/spec/unit/knife/ssl_fetch_spec.rb
+++ b/spec/unit/knife/ssl_fetch_spec.rb
@@ -68,11 +68,11 @@ describe Chef::Knife::SslFetch do
it "prints an error and exits" do
expect { ssl_fetch.run }.to raise_error(SystemExit)
- expected_stdout = <<-E
-USAGE: knife ssl fetch [URL] (options)
+ expected_stdout = <<~E
+ USAGE: knife ssl fetch [URL] (options)
E
- expected_stderr = <<-E
-ERROR: Given URI: `foo.test' is invalid
+ expected_stderr = <<~E
+ ERROR: Given URI: `foo.test' is invalid
E
expect(stdout_io.string).to eq(expected_stdout)
expect(stderr_io.string).to eq(expected_stderr)
@@ -84,11 +84,11 @@ E
it "prints an error and exits" do
expect { ssl_fetch.run }.to raise_error(SystemExit)
- expected_stdout = <<-E
-USAGE: knife ssl fetch [URL] (options)
+ expected_stdout = <<~E
+ USAGE: knife ssl fetch [URL] (options)
E
- expected_stderr = <<-E
-ERROR: Given URI: `#{name_args[0]}' is invalid
+ expected_stderr = <<~E
+ ERROR: Given URI: `#{name_args[0]}' is invalid
E
expect(stdout_io.string).to eq(expected_stdout)
expect(stderr_io.string).to eq(expected_stderr)
@@ -187,9 +187,9 @@ E
end
it "tells the user their URL is for a non-ssl service" do
- expected_error_text = <<-ERROR_TEXT
-ERROR: The service at the given URI (http://foo.example.com) does not accept SSL connections
-ERROR: Perhaps you meant to connect to 'https://foo.example.com'?
+ expected_error_text = <<~ERROR_TEXT
+ ERROR: The service at the given URI (http://foo.example.com) does not accept SSL connections
+ ERROR: Perhaps you meant to connect to 'https://foo.example.com'?
ERROR_TEXT
run
diff --git a/spec/unit/knife/cookbook_site_download_spec.rb b/spec/unit/knife/supermarket_download_spec.rb
index 0ab6a8a9b4..0332bd4390 100644
--- a/spec/unit/knife/cookbook_site_download_spec.rb
+++ b/spec/unit/knife/supermarket_download_spec.rb
@@ -1,6 +1,7 @@
#
# Author:: Thomas Bishop (<bishop.thomas@gmail.com>)
# Copyright:: Copyright 2012-2016, Thomas Bishop
+# Copyright:: Copyright 2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,13 +17,14 @@
# limitations under the License.
#
-require File.expand_path(File.dirname(__FILE__) + "/../../spec_helper")
+require "chef/knife/supermarket_download"
+require "spec_helper"
-describe Chef::Knife::CookbookSiteDownload do
+describe Chef::Knife::SupermarketDownload do
describe "run" do
before do
- @knife = Chef::Knife::CookbookSiteDownload.new
+ @knife = Chef::Knife::SupermarketDownload.new
@knife.name_args = ["apache2"]
@noauth_rest = double("no auth rest")
@stderr = StringIO.new
@@ -35,9 +37,9 @@ 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)
+ expect(@noauth_rest).to receive(:get)
+ .with("#{@cookbook_api_url}/apache2")
+ .and_return(@current_data)
@knife.configure_chef
end
@@ -47,10 +49,10 @@ describe Chef::Knife::CookbookSiteDownload do
end
it "should warn with info about the replacement" do
- expect(@knife.ui).to receive(:warn).
- with(/.+deprecated.+replaced by other_apache2.+/i)
- expect(@knife.ui).to receive(:warn).
- with(/use --force.+download.+/i)
+ expect(@knife.ui).to receive(:warn)
+ .with(/.+deprecated.+replaced by other_apache2.+/i)
+ expect(@knife.ui).to receive(:warn)
+ .with(/use --force.+download.+/i)
@knife.run
end
end
@@ -59,18 +61,18 @@ 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")
end
context "downloading the latest version" do
before do
- expect(@noauth_rest).to receive(:get).
- with(@current_data["latest_version"]).
- and_return(@cookbook_data)
- expect(@noauth_rest).to receive(:streaming_request).
- with(@cookbook_data["file"]).
- and_return(@temp_file)
+ expect(@noauth_rest).to receive(:get)
+ .with(@current_data["latest_version"])
+ .and_return(@cookbook_data)
+ expect(@noauth_rest).to receive(:streaming_request)
+ .with(@cookbook_data["file"])
+ .and_return(@temp_file)
end
context "and it is deprecated and with --force" do
@@ -80,8 +82,8 @@ describe Chef::Knife::CookbookSiteDownload do
end
it "should download the latest version" do
- expect(@knife.ui).to receive(:warn).
- with(/.+deprecated.+replaced by other_apache2.+/i)
+ expect(@knife.ui).to receive(:warn)
+ .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
@@ -124,18 +126,18 @@ describe Chef::Knife::CookbookSiteDownload do
@version_us = @version.tr ".", "_"
@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")
@knife.name_args << @version
end
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)
- expect(@noauth_rest).to receive(:streaming_request).
- with(@cookbook_data["file"]).
- and_return(@temp_file)
+ expect(@noauth_rest).to receive(:get)
+ .with("#{@cookbook_api_url}/apache2/versions/#{@version_us}")
+ .and_return(@cookbook_data)
+ expect(@noauth_rest).to receive(:streaming_request)
+ .with(@cookbook_data["file"])
+ .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
diff --git a/spec/unit/knife/cookbook_site_install_spec.rb b/spec/unit/knife/supermarket_install_spec.rb
index d93af10761..68c8af1028 100644
--- a/spec/unit/knife/cookbook_site_install_spec.rb
+++ b/spec/unit/knife/supermarket_install_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Steven Danna (<steve@chef.io>)
-# Copyright:: Copyright 2011-2016, Chef Software, Inc.
+# Copyright:: Copyright 2011-2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,18 +16,19 @@
# limitations under the License.
#
-require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
+require "spec_helper"
+require "chef/knife/supermarket_install"
-describe Chef::Knife::CookbookSiteInstall do
- let(:knife) { Chef::Knife::CookbookSiteInstall.new }
+describe Chef::Knife::SupermarketInstall do
+ let(:knife) { Chef::Knife::SupermarketInstall.new }
let(:stdout) { StringIO.new }
let(:stderr) { StringIO.new }
let(:downloader) { Hash.new }
let(:archive) { double(Mixlib::Archive, extract: true) }
let(:repo) do
- double(:sanity_check => true, :reset_to_default_state => true,
- :prepare_to_import => true, :finalize_updates_to => true,
- :merge_updates_from => true) end
+ double(sanity_check: true, reset_to_default_state: true,
+ prepare_to_import: true, finalize_updates_to: true,
+ merge_updates_from: true) end
let(:install_path) do
if Chef::Platform.windows?
"C:/tmp/chef"
@@ -52,7 +53,7 @@ describe Chef::Knife::CookbookSiteInstall do
allow(knife).to receive(:shell_out!).and_return(true)
allow(Mixlib::Archive).to receive(:new).and_return(archive)
- # CookbookSiteDownload Stup
+ # SupermarketDownload Setup
allow(knife).to receive(:download_cookbook_to).and_return(downloader)
allow(downloader).to receive(:version) do
if knife.name_args.size == 2
@@ -173,7 +174,7 @@ describe Chef::Knife::CookbookSiteInstall do
it "returns a populated Metadata object if metadata.json exists" do
allow(File).to receive(:exist?).with(json_metadata_path).and_return(true)
- #expect(IO).to receive(:read).with(json_metadata_path)
+ # expect(IO).to receive(:read).with(json_metadata_path)
allow(IO).to receive(:read)
expect(metadata).to receive(:from_json)
knife.preferred_metadata
diff --git a/spec/unit/knife/cookbook_site_share_spec.rb b/spec/unit/knife/supermarket_share_spec.rb
index 823eff8b04..dde58775f4 100644
--- a/spec/unit/knife/cookbook_site_share_spec.rb
+++ b/spec/unit/knife/supermarket_share_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Stephen Delano (<stephen@chef.io>)
-# Copyright:: Copyright 2010-2016, Chef Software Inc.
+# Copyright:: Copyright 2010-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,14 +17,14 @@
#
require "spec_helper"
-
+require "chef/knife/supermarket_share"
require "chef/cookbook_uploader"
require "chef/cookbook_site_streaming_uploader"
-describe Chef::Knife::CookbookSiteShare do
+describe Chef::Knife::SupermarketShare do
before(:each) do
- @knife = Chef::Knife::CookbookSiteShare.new
+ @knife = Chef::Knife::SupermarketShare.new
# Merge default settings in.
@knife.merge_configs
@knife.name_args = %w{cookbook_name AwesomeSausage}
@@ -39,7 +39,7 @@ describe Chef::Knife::CookbookSiteShare do
@noauth_rest = double(Chef::ServerAPI)
allow(@knife).to receive(:noauth_rest).and_return(@noauth_rest)
- @cookbook_uploader = Chef::CookbookUploader.new("herpderp", :rest => "norest")
+ @cookbook_uploader = Chef::CookbookUploader.new("herpderp", rest: "norest")
allow(Chef::CookbookUploader).to receive(:new).and_return(@cookbook_uploader)
allow(@cookbook_uploader).to receive(:validate_cookbooks).and_return(true)
allow(Chef::CookbookSiteStreamingUploader).to receive(:create_build_dir).and_return(Dir.mktmpdir)
@@ -139,14 +139,14 @@ describe Chef::Knife::CookbookSiteShare do
context "when the --dry-run flag is specified" do
before do
allow(Chef::CookbookSiteStreamingUploader).to receive(:create_build_dir).and_return("/var/tmp/dummy")
- @knife.config = { :dry_run => true }
+ @knife.config = { dry_run: true }
allow(@knife).to receive_message_chain(:shell_out!, :stdout).and_return("file")
end
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
@@ -172,7 +172,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 +180,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 +188,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,11 +196,11 @@ 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.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
diff --git a/spec/unit/knife/cookbook_site_unshare_spec.rb b/spec/unit/knife/supermarket_unshare_spec.rb
index 8e4358226d..206717e211 100644
--- a/spec/unit/knife/cookbook_site_unshare_spec.rb
+++ b/spec/unit/knife/supermarket_unshare_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Stephen Delano (<stephen@chef.io>)
# Author:: Tim Hinderliter (<tim@chef.io>)
-# Copyright:: Copyright 2010-2016, Chef Software Inc.
+# Copyright:: Copyright 2010-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,11 +18,12 @@
#
require "spec_helper"
+require "chef/knife/supermarket_unshare"
-describe Chef::Knife::CookbookSiteUnshare do
+describe Chef::Knife::SupermarketUnshare do
before(:each) do
- @knife = Chef::Knife::CookbookSiteUnshare.new
+ @knife = Chef::Knife::SupermarketUnshare.new
@knife.name_args = ["cookbook_name"]
allow(@knife).to receive(:confirm).and_return(true)
@@ -55,14 +56,14 @@ describe Chef::Knife::CookbookSiteUnshare do
end
it "should log an error and exit when forbidden" do
- exception = double('403 "Forbidden"', :code => "403")
+ exception = double('403 "Forbidden"', code: "403")
allow(@rest).to receive(:delete).and_raise(Net::HTTPServerException.new('403 "Forbidden"', exception))
expect(@knife.ui).to receive(:error)
expect { @knife.run }.to raise_error(SystemExit)
end
it "should re-raise any non-forbidden errors on delete" do
- exception = double('500 "Application Error"', :code => "500")
+ exception = double('500 "Application Error"', code: "500")
allow(@rest).to receive(:delete).and_raise(Net::HTTPServerException.new('500 "Application Error"', exception))
expect { @knife.run }.to raise_error(Net::HTTPServerException)
end
diff --git a/spec/unit/knife/user_delete_spec.rb b/spec/unit/knife/user_delete_spec.rb
index 0f71b39a41..68749fe727 100644
--- a/spec/unit/knife/user_delete_spec.rb
+++ b/spec/unit/knife/user_delete_spec.rb
@@ -51,7 +51,7 @@ describe Chef::Knife::UserDelete do
end
it "deletes the user" do
- #expect(knife).to receive(:delete_object).with(Chef::UserV1, 'my_user')
+ # expect(knife).to receive(:delete_object).with(Chef::UserV1, 'my_user')
expect(knife).to receive(:delete_object).with("my_user")
knife.run
end
diff --git a/spec/unit/knife/user_reregister_spec.rb b/spec/unit/knife/user_reregister_spec.rb
index d650ff9fb8..8501347087 100644
--- a/spec/unit/knife/user_reregister_spec.rb
+++ b/spec/unit/knife/user_reregister_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Knife::UserReregister do
let(:knife) { Chef::Knife::UserReregister.new }
- let(:user_mock) { double("user_mock", :private_key => "private_key") }
+ let(:user_mock) { double("user_mock", private_key: "private_key") }
let(:stdout) { StringIO.new }
before do
diff --git a/spec/unit/knife_spec.rb b/spec/unit/knife_spec.rb
index 2b22dbc4f7..c091286077 100644
--- a/spec/unit/knife_spec.rb
+++ b/spec/unit/knife_spec.rb
@@ -37,7 +37,7 @@ describe Chef::Knife do
instance_double("WorkstationConfigLoader",
load: nil, no_config_found?: false,
config_location: config_location,
- :chef_config_dir => "/etc/chef")
+ chef_config_dir: "/etc/chef")
end
before(:each) do
@@ -47,6 +47,7 @@ describe Chef::Knife do
allow(Chef::WorkstationConfigLoader).to receive(:new).and_return(config_loader)
allow(config_loader).to receive(:explicit_config_file=)
+ allow(config_loader).to receive(:profile=)
# Prevent gratuitous code reloading:
allow(Chef::Knife).to receive(:load_commands)
@@ -224,10 +225,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)
@@ -282,8 +283,8 @@ describe Chef::Knife do
describe "merging configuration options" do
before do
KnifeSpecs::TestYourself.option(:opt_with_default,
- :short => "-D VALUE",
- :default => "default-value")
+ short: "-D VALUE",
+ default: "default-value")
end
it "sets the default log_location to STDERR for Chef::Log warnings" do
@@ -299,14 +300,14 @@ describe Chef::Knife do
end
it "prefers the default value if no config or command line value is present" do
- knife_command = KnifeSpecs::TestYourself.new([]) #empty argv
+ knife_command = KnifeSpecs::TestYourself.new([]) # empty argv
knife_command.configure_chef
expect(knife_command.config[:opt_with_default]).to eq("default-value")
end
it "prefers a value in Chef::Config[:knife] to the default" do
Chef::Config[:knife][:opt_with_default] = "from-knife-config"
- knife_command = KnifeSpecs::TestYourself.new([]) #empty argv
+ knife_command = KnifeSpecs::TestYourself.new([]) # empty argv
knife_command.configure_chef
expect(knife_command.config[:opt_with_default]).to eq("from-knife-config")
end
@@ -329,8 +330,9 @@ describe Chef::Knife do
before do
knife.config[:verbosity] = 1
knife.config[:config_file] = fake_config
- config_loader = double("Chef::WorkstationConfigLoader", :load => true, :no_config_found? => false, :chef_config_dir => "/etc/chef", :config_location => fake_config)
+ config_loader = double("Chef::WorkstationConfigLoader", load: true, no_config_found?: false, chef_config_dir: "/etc/chef", config_location: fake_config)
allow(config_loader).to receive(:explicit_config_file=).with(fake_config).and_return(fake_config)
+ allow(config_loader).to receive(:profile=)
allow(Chef::WorkstationConfigLoader).to receive(:new).and_return(config_loader)
end
@@ -421,7 +423,7 @@ describe Chef::Knife do
it "formats 401s nicely" do
response = Net::HTTPUnauthorized.new("1.1", "401", "Unauthorized")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no syncronize your clock?"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "y u no syncronize your clock?"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("401 Unauthorized", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(/ERROR: Failed to authenticate to/)
@@ -431,7 +433,7 @@ describe Chef::Knife do
it "formats 403s nicely" do
response = Net::HTTPForbidden.new("1.1", "403", "Forbidden")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no administrator"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "y u no administrator"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("403 Forbidden", response))
allow(knife).to receive(:username).and_return("sadpanda")
knife.run_with_pretty_exceptions
@@ -451,7 +453,7 @@ describe Chef::Knife do
it "formats proxy errors nicely" do
response = Net::HTTPForbidden.new("1.1", "403", "Forbidden")
response.instance_variable_set(:@read, true)
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u no administrator"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "y u no administrator"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("403 Forbidden", response))
allow(knife).to receive(:username).and_return("sadpanda")
knife.run_with_pretty_exceptions
@@ -464,7 +466,7 @@ describe Chef::Knife do
it "formats 400s nicely" do
response = Net::HTTPBadRequest.new("1.1", "400", "Bad Request")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "y u search wrong"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "y u search wrong"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("400 Bad Request", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: The data in your request was invalid})
@@ -474,7 +476,7 @@ describe Chef::Knife do
it "formats 404s nicely" do
response = Net::HTTPNotFound.new("1.1", "404", "Not Found")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "nothing to see here"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "nothing to see here"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("404 Not Found", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: The object you are looking for could not be found})
@@ -486,9 +488,9 @@ describe Chef::Knife do
response.instance_variable_set(:@read, true) # I hate you, net/http.
# set the header
- response["x-ops-server-api-version"] = Chef::JSONCompat.to_json(:min_version => "0", :max_version => "1", :request_version => "10000000")
+ response["x-ops-server-api-version"] = Chef::JSONCompat.to_json(min_version: "0", max_version: "1", request_version: "10000000")
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "sad trombone"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "sad trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("406 Not Acceptable", response))
knife.run_with_pretty_exceptions
@@ -500,7 +502,7 @@ describe Chef::Knife do
it "formats 500s nicely" do
response = Net::HTTPInternalServerError.new("1.1", "500", "Internal Server Error")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "sad trombone"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "sad trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("500 Internal Server Error", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: internal server error})
@@ -510,7 +512,7 @@ describe Chef::Knife do
it "formats 502s nicely" do
response = Net::HTTPBadGateway.new("1.1", "502", "Bad Gateway")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "sadder trombone"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "sadder trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("502 Bad Gateway", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: bad gateway})
@@ -520,7 +522,7 @@ describe Chef::Knife do
it "formats 503s nicely" do
response = Net::HTTPServiceUnavailable.new("1.1", "503", "Service Unavailable")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "saddest trombone"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "saddest trombone"))
allow(knife).to receive(:run).and_raise(Net::HTTPFatalError.new("503 Service Unavailable", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: Service temporarily unavailable})
@@ -530,7 +532,7 @@ describe Chef::Knife do
it "formats other HTTP errors nicely" do
response = Net::HTTPPaymentRequired.new("1.1", "402", "Payment Required")
response.instance_variable_set(:@read, true) # I hate you, net/http.
- allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(:error => "nobugfixtillyoubuy"))
+ allow(response).to receive(:body).and_return(Chef::JSONCompat.to_json(error: "nobugfixtillyoubuy"))
allow(knife).to receive(:run).and_raise(Net::HTTPServerException.new("402 Payment Required", response))
knife.run_with_pretty_exceptions
expect(stderr.string).to match(%r{ERROR: Payment Required})
@@ -569,11 +571,11 @@ describe Chef::Knife do
knife.run_with_pretty_exceptions
- 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
-`knife ssl fetch` to make knife trust the server's certificates.
+ 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
+ `knife ssl fetch` to make knife trust the server's certificates.
MSG
expect(stderr.string).to include(expected_message)
end
diff --git a/spec/unit/log/syslog_spec.rb b/spec/unit/log/syslog_spec.rb
index ebf1418576..4586503e88 100644
--- a/spec/unit/log/syslog_spec.rb
+++ b/spec/unit/log/syslog_spec.rb
@@ -17,11 +17,9 @@
#
require "spec_helper"
-require "chef"
-describe "Chef::Log::Syslog", :unix_only => true do
+describe "Chef::Log::Syslog", unix_only: true do
let(:syslog) { Chef::Log::Syslog.new }
- let(:app) { Chef::Application.new }
before do
Chef::Log.init(MonoLogger.new(syslog))
@@ -37,12 +35,12 @@ describe "Chef::Log::Syslog", :unix_only => true do
end
it "should send message with severity info to syslog." do
- expect(syslog).to receive(:info).with("*** Chef 12.4.0.dev.0 ***")
+ expect(syslog).to receive(:add).with(1, "*** Chef 12.4.0.dev.0 ***", nil)
Chef::Log.info("*** Chef 12.4.0.dev.0 ***")
end
it "should send message with severity warning to syslog." do
- expect(syslog).to receive(:warn).with("No config file found or specified on command line, using command line options.")
+ expect(syslog).to receive(:add).with(2, "No config file found or specified on command line, using command line options.", nil)
Chef::Log.warn("No config file found or specified on command line, using command line options.")
end
diff --git a/spec/unit/log/winevt_spec.rb b/spec/unit/log/winevt_spec.rb
index d5d452159b..c7cc49f40d 100644
--- a/spec/unit/log/winevt_spec.rb
+++ b/spec/unit/log/winevt_spec.rb
@@ -25,7 +25,6 @@ describe Chef::Log::WinEvt do
let(:app) { Chef::Application.new }
before do
-
Chef::Log.init(MonoLogger.new(winevt))
@old_log_level = Chef::Log.level
Chef::Log.level = :info
@@ -39,12 +38,12 @@ describe Chef::Log::WinEvt do
end
it "should send message with severity info to Windows Event Log." do
- expect(winevt).to receive(:info).with("*** Chef 12.4.0.dev.0 ***")
+ expect(winevt).to receive(:add).with(1, "*** Chef 12.4.0.dev.0 ***", nil)
Chef::Log.info("*** Chef 12.4.0.dev.0 ***")
end
it "should send message with severity warning to Windows Event Log." do
- expect(winevt).to receive(:warn).with("No config file found or specified on command line, using command line options.")
+ expect(winevt).to receive(:add).with(2, "No config file found or specified on command line, using command line options.", nil)
Chef::Log.warn("No config file found or specified on command line, using command line options.")
end
diff --git a/spec/unit/lwrp_spec.rb b/spec/unit/lwrp_spec.rb
index 75ebbb8f02..a7f95f8bfd 100644
--- a/spec/unit/lwrp_spec.rb
+++ b/spec/unit/lwrp_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Christopher Walters (<cw@chef.io>)
-# Copyright:: Copyright 2009-2017, Chef Software Inc.
+# Copyright:: Copyright 2009-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -57,7 +57,7 @@ describe "LWRP" do
Object.const_set("LwrpFoo", Class.new)
file = File.expand_path( "lwrp/resources/foo.rb", CHEF_SPEC_DATA)
expect(Chef::Log).not_to receive(:info).with(/Skipping/)
- expect(Chef::Log).not_to receive(:debug).with(/anymore/)
+ expect(Chef::Log).not_to receive(:trace).with(/anymore/)
Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil)
Object.send(:remove_const, "LwrpFoo")
end
@@ -66,7 +66,7 @@ describe "LWRP" do
Object.const_set("LwrpBuckPasser", Class.new)
file = File.expand_path( "lwrp/providers/buck_passer.rb", CHEF_SPEC_DATA)
expect(Chef::Log).not_to receive(:info).with(/Skipping/)
- expect(Chef::Log).not_to receive(:debug).with(/anymore/)
+ expect(Chef::Log).not_to receive(:trace).with(/anymore/)
Chef::Provider::LWRPBase.build_from_file("lwrp", file, nil)
Object.send(:remove_const, "LwrpBuckPasser")
end
@@ -81,7 +81,7 @@ describe "LWRP" do
end
Dir[File.expand_path( "lwrp/resources/*", CHEF_SPEC_DATA)].each do |file|
- expect(Chef::Log).to receive(:debug).with(/Skipping/)
+ expect(Chef::Log).to receive(:trace).with(/Skipping/)
Chef::Resource::LWRPBase.build_from_file("lwrp", file, nil)
end
end
@@ -92,7 +92,7 @@ describe "LWRP" do
end
Dir[File.expand_path( "lwrp/providers/*", CHEF_SPEC_DATA)].each do |file|
- expect(Chef::Log).to receive(:debug).with(/Skipping/)
+ expect(Chef::Log).to receive(:trace).with(/Skipping/)
Chef::Provider::LWRPBase.build_from_file("lwrp", file, nil)
end
end
@@ -243,8 +243,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
@@ -520,7 +520,7 @@ describe "LWRP" do
resource.provider(get_dynamic_lwrp_provider(:lwrp_embedded_resource_accesses_providers_scope))
provider = resource.provider_for_action(:twiddle_thumbs)
- #provider = @runner.build_provider(resource)
+ # provider = @runner.build_provider(resource)
provider.action_twiddle_thumbs
expect(provider.enclosed_resource.monkey).to eq("bob, the monkey")
@@ -571,14 +571,16 @@ describe "LWRP" do
context "resource class created" do
let(:test_lwrp_class) { @test_lwrp_class }
- before(:context) do
- @tmpdir = Dir.mktmpdir("lwrp_test")
+ before(:each) do
+ @tmpparent = Dir.mktmpdir("lwrp_test")
+ @tmpdir = File.join(@tmpparent, "lwrp")
+ Dir.mkdir(@tmpdir)
resource_path = File.join(@tmpdir, "once.rb")
IO.write(resource_path, "default_action :create")
@test_lwrp_class = Chef::Resource::LWRPBase.build_from_file("lwrp", resource_path, nil)
end
- after(:context) do
+ after(:each) do
FileUtils.remove_entry @tmpdir
end
diff --git a/spec/unit/mash_spec.rb b/spec/unit/mash_spec.rb
index e58f6b85a1..0797e80f2c 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,7 +30,7 @@ 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)
@@ -39,7 +39,7 @@ describe Mash do
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)
diff --git a/spec/unit/mixin/api_version_request_handling_spec.rb b/spec/unit/mixin/api_version_request_handling_spec.rb
index 191dee643b..cabc85439c 100644
--- a/spec/unit/mixin/api_version_request_handling_spec.rb
+++ b/spec/unit/mixin/api_version_request_handling_spec.rb
@@ -26,24 +26,24 @@ describe Chef::Mixin::ApiVersionRequestHandling do
let(:default_supported_client_versions) { [0, 1, 2] }
context "when the response code is not 406" do
- let(:response) { OpenStruct.new(:code => "405") }
+ let(:response) { OpenStruct.new(code: "405") }
let(:exception) { Net::HTTPServerException.new("405 Something Else", response) }
it "returns nil" do
- expect(object.server_client_api_version_intersection(exception, default_supported_client_versions)).
- to be_nil
+ 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
- let(:response) { OpenStruct.new(:code => "406") }
+ let(:response) { OpenStruct.new(code: "406") }
let(:exception) { Net::HTTPServerException.new("406 Not Acceptable", response) }
context "when x-ops-server-api-version header does not exist" do
it "returns nil" do
- expect(object.server_client_api_version_intersection(exception, default_supported_client_versions)).
- to be_nil
+ expect(object.server_client_api_version_intersection(exception, default_supported_client_versions))
+ .to be_nil
end
end # when x-ops-server-api-version header does not exist
@@ -64,13 +64,13 @@ describe Chef::Mixin::ApiVersionRequestHandling do
context "when there is no intersection between client and server versions" do
shared_examples_for "no intersection between client and server versions" do
it "return an array" do
- expect(object.server_client_api_version_intersection(exception, supported_client_versions)).
- to be_a_kind_of(Array)
+ expect(object.server_client_api_version_intersection(exception, supported_client_versions))
+ .to be_a_kind_of(Array)
end
it "returns an empty array" do
- expect(object.server_client_api_version_intersection(exception, supported_client_versions).length).
- to eq(0)
+ expect(object.server_client_api_version_intersection(exception, supported_client_versions).length)
+ .to eq(0)
end
end
@@ -94,8 +94,8 @@ describe Chef::Mixin::ApiVersionRequestHandling do
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])
+ expect(object.server_client_api_version_intersection(exception, supported_client_versions))
+ .to eq([2, 3, 4])
end
end # when multiple versions intersect
@@ -103,8 +103,8 @@ describe Chef::Mixin::ApiVersionRequestHandling do
let(:supported_client_versions) { [0, 1, 2] }
it "includes the intersection" do
- expect(object.server_client_api_version_intersection(exception, supported_client_versions)).
- to eq([2])
+ expect(object.server_client_api_version_intersection(exception, supported_client_versions))
+ .to eq([2])
end
end # when only the min client version intersects
@@ -112,8 +112,8 @@ describe Chef::Mixin::ApiVersionRequestHandling do
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])
+ expect(object.server_client_api_version_intersection(exception, supported_client_versions))
+ .to eq([4])
end
end # when only the max client version intersects
diff --git a/spec/unit/mixin/checksum_spec.rb b/spec/unit/mixin/checksum_spec.rb
index 801c8820d2..873d2a2fc0 100644
--- a/spec/unit/mixin/checksum_spec.rb
+++ b/spec/unit/mixin/checksum_spec.rb
@@ -29,7 +29,7 @@ describe Chef::Mixin::Checksum do
@checksum_user = Chef::CMCCheck.new
@cache = Chef::Digester.instance
@file = CHEF_SPEC_DATA + "/checksum/random.txt"
- @stat = double("File::Stat", { :mtime => Time.at(0) })
+ @stat = double("File::Stat", { mtime: Time.at(0) })
allow(File).to receive(:stat).and_return(@stat)
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..701de06167 100644
--- a/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb
+++ b/spec/unit/mixin/enforce_ownership_and_permissions_spec.rb
@@ -51,11 +51,11 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do
allow_any_instance_of(Chef::FileAccessControl).to receive(:define_resource_requirements)
allow_any_instance_of(Chef::FileAccessControl).to receive(:describe_changes)
- passwd_struct = OpenStruct.new(:name => "root", :passwd => "x",
- :uid => 0, :gid => 0, :dir => "/root",
- :shell => "/bin/bash")
+ passwd_struct = OpenStruct.new(name: "root", passwd: "x",
+ uid: 0, gid: 0, dir: "/root",
+ shell: "/bin/bash")
- group_struct = OpenStruct.new(:name => "root", :passwd => "x", :gid => 0)
+ group_struct = OpenStruct.new(name: "root", passwd: "x", gid: 0)
allow(Etc).to receive(:getpwuid).and_return(passwd_struct)
allow(Etc).to receive(:getgrgid).and_return(group_struct)
end
@@ -75,11 +75,11 @@ describe Chef::Mixin::EnforceOwnershipAndPermissions do
allow_any_instance_of(Chef::FileAccessControl).to receive(:uid_from_resource).and_return(0)
allow_any_instance_of(Chef::FileAccessControl).to receive(:describe_changes)
- passwd_struct = OpenStruct.new(:name => "root", :passwd => "x",
- :uid => 0, :gid => 0, :dir => "/root",
- :shell => "/bin/bash")
+ passwd_struct = OpenStruct.new(name: "root", passwd: "x",
+ uid: 0, gid: 0, dir: "/root",
+ shell: "/bin/bash")
- group_struct = OpenStruct.new(:name => "root", :passwd => "x", :gid => 0)
+ group_struct = OpenStruct.new(name: "root", passwd: "x", gid: 0)
allow(Etc).to receive(:getpwuid).and_return(passwd_struct)
allow(Etc).to receive(:getgrgid).and_return(group_struct)
end
diff --git a/spec/unit/mixin/homebrew_user_spec.rb b/spec/unit/mixin/homebrew_user_spec.rb
index c9a6e6e909..df89962cce 100644
--- a/spec/unit/mixin/homebrew_user_spec.rb
+++ b/spec/unit/mixin/homebrew_user_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Joshua Timberman (<joshua@chef.io>)
#
-# Copyright 2014-2016, Chef Software, Inc <legal@chef.io>
+# Copyright 2014-2018, Chef Software, Inc <legal@chef.io>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -23,10 +23,6 @@ class ExampleHomebrewUser
end
describe Chef::Mixin::HomebrewUser do
- before(:each) do
- node.default["homebrew"]["owner"] = nil
- end
-
let(:homebrew_user) { ExampleHomebrewUser.new }
let(:node) { Chef::Node.new }
@@ -60,7 +56,7 @@ 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"))
+ expect(Etc).to receive(:getpwuid).with(brew_owner).and_return(OpenStruct.new(name: "name"))
end
it "returns the owner of the brew executable when it is at a default location" do
diff --git a/spec/unit/mixin/openssl_helper_spec.rb b/spec/unit/mixin/openssl_helper_spec.rb
new file mode 100644
index 0000000000..6873fd8cf2
--- /dev/null
+++ b/spec/unit/mixin/openssl_helper_spec.rb
@@ -0,0 +1,252 @@
+#
+# Copyright 2009-2018, Chef Software, Inc <legal@chef.io>
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+require "spec_helper"
+require "chef/mixin/openssl_helper"
+
+describe Chef::Mixin::OpenSSLHelper do
+ let(:instance) do
+ Class.new { include Chef::Mixin::OpenSSLHelper }.new
+ end
+
+ describe ".included" do
+ it "requires openssl" do
+ instance
+ expect(defined?(OpenSSL)).to_not be(false)
+ end
+ end
+
+ # Path helpers
+ describe "#get_key_filename" do
+ context "When the input is not a string" do
+ it "Throws a TypeError" do
+ expect do
+ instance.get_key_filename(33)
+ end.to raise_error(TypeError)
+ end
+ end
+
+ context "when the input is a string" do
+ it "Generates valid keyfile names" do
+ expect(instance.get_key_filename("/etc/temp.crt")).to match("/etc/temp.key")
+ end
+ end
+ end
+
+ # Validation helpers
+ describe "#key_length_valid?" do
+ context "When the number is less than 1024" do
+ it "returns false" do
+ expect(instance.key_length_valid?(1023)).to be_falsey
+ expect(instance.key_length_valid?(2)).to be_falsey
+ expect(instance.key_length_valid?(64)).to be_falsey
+ expect(instance.key_length_valid?(512)).to be_falsey
+ end
+ end
+
+ context "When the number is greater than 1024 but is not a power of 2" do
+ it "returns false" do
+ expect(instance.key_length_valid?(1025)).to be_falsey
+ expect(instance.key_length_valid?(6666)).to be_falsey
+ expect(instance.key_length_valid?(8191)).to be_falsey
+ end
+ end
+
+ context "When the number is a power of 2, equal to or greater than 1024" do
+ it "returns true" do
+ expect(instance.key_length_valid?(1024)).to be_truthy
+ expect(instance.key_length_valid?(2048)).to be_truthy
+ expect(instance.key_length_valid?(4096)).to be_truthy
+ expect(instance.key_length_valid?(8192)).to be_truthy
+ end
+ end
+ end
+
+ describe "#dhparam_pem_valid?" do
+ require "tempfile"
+
+ before(:each) do
+ @dhparam_file = Tempfile.new("dhparam")
+ end
+
+ context "When the dhparam.pem file does not exist" do
+ it "returns false" do
+ expect(instance.dhparam_pem_valid?("/tmp/bad_filename")).to be_falsey
+ end
+ end
+
+ context "When the dhparam.pem file does exist, but does not contain a valid dhparam key" do
+ it "Throws an OpenSSL::PKey::DHError exception" do
+ expect do
+ @dhparam_file.puts("I_am_not_a_key_I_am_a_free_man")
+ @dhparam_file.close
+ instance.dhparam_pem_valid?(@dhparam_file.path)
+ end.to raise_error(::OpenSSL::PKey::DHError)
+ end
+ end
+
+ context "When the dhparam.pem file does exist, and does contain a vaild dhparam key" do
+ it "returns true" do
+ @dhparam_file.puts(::OpenSSL::PKey::DH.new(1024).to_pem)
+ @dhparam_file.close
+ expect(instance.dhparam_pem_valid?(@dhparam_file.path)).to be_truthy
+ end
+ end
+
+ after(:each) do
+ @dhparam_file.unlink
+ end
+ end
+
+ describe "#priv_key_file_valid?" do
+ require "tempfile"
+ require "openssl" unless defined?(OpenSSL)
+
+ cipher = ::OpenSSL::Cipher.new("des3")
+
+ before(:each) do
+ @keyfile = Tempfile.new("keyfile")
+ end
+
+ context "When the key file does not exist" do
+ it "returns false" do
+ expect(instance.priv_key_file_valid?("/tmp/bad_filename")).to be_falsey
+ end
+ end
+
+ context "When the key file does exist, but does not contain a valid rsa private key" do
+ it "Throws an OpenSSL::PKey::RSAError exception" do
+ @keyfile.write("I_am_not_a_key_I_am_a_free_man")
+ @keyfile.close
+ expect(instance.priv_key_file_valid?(@keyfile.path)).to be_falsey
+ end
+ end
+
+ context "When the key file does exist, and does contain a vaild rsa private key" do
+ it "returns true" do
+ @keyfile.write(::OpenSSL::PKey::RSA.new(1024).to_pem)
+ @keyfile.close
+ expect(instance.priv_key_file_valid?(@keyfile.path)).to be_truthy
+ end
+ end
+
+ context "When a valid keyfile requires a passphrase, and an invalid passphrase is supplied" do
+ it "returns false" do
+ @keyfile.write(::OpenSSL::PKey::RSA.new(1024).to_pem(cipher, "oink"))
+ @keyfile.close
+ expect(instance.priv_key_file_valid?(@keyfile.path, "poml")).to be_falsey
+ end
+ end
+
+ context "When a valid keyfile requires a passphrase, and a valid passphrase is supplied" do
+ it "returns true" do
+ @keyfile.write(::OpenSSL::PKey::RSA.new(1024).to_pem(cipher, "oink"))
+ @keyfile.close
+ expect(instance.priv_key_file_valid?(@keyfile.path, "oink")).to be_truthy
+ end
+ end
+
+ after(:each) do
+ @keyfile.unlink
+ end
+ end
+
+ # Generators
+ describe "#gen_dhparam" do
+ context "When given an invalid key length" do
+ it "Throws an ArgumentError" do
+ expect do
+ instance.gen_dhparam(2046, 2)
+ end.to raise_error(ArgumentError)
+ end
+ end
+
+ context "When given an invalid generator id" do
+ it "Throws a TypeError" do
+ expect do
+ instance.gen_dhparam(2048, "bob")
+ end.to raise_error(TypeError)
+ end
+ end
+
+ context "When a proper key length and generator id are given" do
+ it "Generates a dhparam object" do
+ expect(instance.gen_dhparam(1024, 2)).to be_kind_of(::OpenSSL::PKey::DH)
+ end
+ end
+ end
+
+ describe "#gen_rsa_priv_key" do
+ context "When given an invalid key length" do
+ it "Throws an ArgumentError" do
+ expect do
+ instance.gen_rsa_priv_key(4093)
+ end.to raise_error(ArgumentError)
+ end
+ end
+
+ context "When a proper key length is given" do
+ it "Generates an RSA key object" do
+ expect(instance.gen_rsa_priv_key(1024)).to be_kind_of(::OpenSSL::PKey::RSA)
+ end
+ end
+ end
+
+ describe "#encrypt_rsa_key" do
+ before(:all) do
+ @rsa_key = ::OpenSSL::PKey::RSA.new(1024)
+ end
+
+ context "When given anything other than an RSA key object to encrypt" do
+ it "Raises a TypeError" do
+ expect do
+ instance.encrypt_rsa_key("abcd", "efgh", "des3")
+ end.to raise_error(TypeError)
+ end
+ end
+
+ context "When given anything other than a string as the passphrase" do
+ it "Raises a TypeError" do
+ expect do
+ instance.encrypt_rsa_key(@rsa_key, 1234, "des3")
+ end.to raise_error(TypeError)
+ end
+ end
+
+ context "When given anything other than a string as the cipher" do
+ it "Raises a TypeError" do
+ expect do
+ instance.encrypt_rsa_key(@rsa_key, "1234", 1234)
+ end.to raise_error(TypeError)
+ end
+ end
+
+ context "When given an invalid cipher string" do
+ it "Raises an ArgumentError" do
+ expect do
+ instance.encrypt_rsa_key(@rsa_key, "1234", "des3_bogus")
+ end.to raise_error(ArgumentError)
+ end
+ end
+
+ context "When given a valid RSA key and a valid passphrase string" do
+ it "Generates a valid encrypted PEM" do
+ @encrypted_key = instance.encrypt_rsa_key(@rsa_key, "oink", "des3")
+ expect(@encrypted_key).to be_kind_of(String)
+ expect(::OpenSSL::PKey::RSA.new(@encrypted_key, "oink").private?).to be_truthy
+ end
+ end
+ end
+end
diff --git a/spec/unit/mixin/params_validate_spec.rb b/spec/unit/mixin/params_validate_spec.rb
index 0cafb925c8..62d6b3e117 100644
--- a/spec/unit/mixin/params_validate_spec.rb
+++ b/spec/unit/mixin/params_validate_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -34,7 +34,7 @@ describe Chef::Mixin::ParamsValidate do
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,26 +42,26 @@ 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 do
@vo.validate(
- { :one => "string" },
+ { one: "string" },
{
- :one => {
- :kind_of => String,
+ one: {
+ kind_of: String,
},
}
)
@@ -69,10 +69,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :one => "string" },
+ { one: "string" },
{
- :one => {
- :kind_of => Array,
+ one: {
+ kind_of: Array,
},
}
)
@@ -82,10 +82,10 @@ describe Chef::Mixin::ParamsValidate do
it "should allow you to specify an argument is required with required" do
expect do
@vo.validate(
- { :one => "string" },
+ { one: "string" },
{
- :one => {
- :required => true,
+ one: {
+ required: true,
},
}
)
@@ -93,10 +93,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :two => "string" },
+ { two: "string" },
{
- :one => {
- :required => true,
+ one: {
+ required: true,
},
}
)
@@ -104,10 +104,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :two => "string" },
+ { two: "string" },
{
- :one => {
- :required => false,
+ one: {
+ required: false,
},
}
)
@@ -117,10 +117,10 @@ describe Chef::Mixin::ParamsValidate do
it "should allow you to specify whether an object has a method with respond_to" do
expect do
@vo.validate(
- { :one => @vo },
+ { one: @vo },
{
- :one => {
- :respond_to => "validate",
+ one: {
+ respond_to: "validate",
},
}
)
@@ -128,10 +128,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :one => @vo },
+ { one: @vo },
{
- :one => {
- :respond_to => "monkey",
+ one: {
+ respond_to: "monkey",
},
}
)
@@ -141,10 +141,10 @@ 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 do
@vo.validate(
- { :one => @vo },
+ { one: @vo },
{
- :one => {
- :respond_to => %w{validate music},
+ one: {
+ respond_to: %w{validate music},
},
}
)
@@ -152,10 +152,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :one => @vo },
+ { one: @vo },
{
- :one => {
- :respond_to => %w{monkey validate},
+ one: {
+ respond_to: %w{monkey validate},
},
}
)
@@ -165,8 +165,8 @@ 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")
@@ -175,10 +175,10 @@ describe Chef::Mixin::ParamsValidate do
it "should let you check regular expressions" do
expect do
@vo.validate(
- { :one => "is good" },
+ { one: "is good" },
{
- :one => {
- :regex => /^is good$/,
+ one: {
+ regex: /^is good$/,
},
}
)
@@ -186,10 +186,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :one => "is good" },
+ { one: "is good" },
{
- :one => {
- :regex => /^is bad$/,
+ one: {
+ regex: /^is bad$/,
},
}
)
@@ -199,10 +199,10 @@ describe Chef::Mixin::ParamsValidate do
it "should let you specify your own callbacks" do
expect do
@vo.validate(
- { :one => "is good" },
+ { one: "is good" },
{
- :one => {
- :callbacks => {
+ one: {
+ callbacks: {
"should be equal to is good" => lambda do |a|
a == "is good"
end,
@@ -214,10 +214,10 @@ describe Chef::Mixin::ParamsValidate do
expect do
@vo.validate(
- { :one => "is bad" },
+ { one: "is bad" },
{
- :one => {
- :callbacks => {
+ one: {
+ callbacks: {
"should be equal to 'is good'" => lambda do |a|
a == "is good"
end,
@@ -229,27 +229,27 @@ describe Chef::Mixin::ParamsValidate do
end
it "should let you combine checks" do
- args = { :one => "is good", :two => "is bad" }
+ args = { one: "is good", two: "is bad" }
expect do
@vo.validate(
args,
{
- :one => {
- :kind_of => String,
- :respond_to => [ :to_s, :upcase ],
- :regex => /^is good/,
- :callbacks => {
+ one: {
+ kind_of: String,
+ respond_to: [ :to_s, :upcase ],
+ regex: /^is good/,
+ callbacks: {
"should be your friend" => lambda do |a|
a == "is good"
end,
},
- :required => true,
+ required: true,
},
- :two => {
- :kind_of => String,
- :required => false,
+ two: {
+ kind_of: String,
+ required: false,
},
- :three => { :default => "neato mosquito" },
+ three: { default: "neato mosquito" },
}
)
end.not_to raise_error
@@ -258,22 +258,22 @@ describe Chef::Mixin::ParamsValidate do
@vo.validate(
args,
{
- :one => {
- :kind_of => String,
- :respond_to => [ :to_s, :upcase ],
- :regex => /^is good/,
- :callbacks => {
+ one: {
+ kind_of: String,
+ respond_to: [ :to_s, :upcase ],
+ regex: /^is good/,
+ callbacks: {
"should be your friend" => lambda do |a|
a == "is good"
end,
},
- :required => true,
+ required: true,
},
- :two => {
- :kind_of => Hash,
- :required => false,
+ two: {
+ kind_of: Hash,
+ required: false,
},
- :three => { :default => "neato mosquito" },
+ three: { default: "neato mosquito" },
}
)
end.to raise_error(ArgumentError)
@@ -282,10 +282,10 @@ describe Chef::Mixin::ParamsValidate do
it "should raise an ArgumentError if the validation map has an unknown check" do
expect do
@vo.validate(
- { :one => "two" },
+ { one: "two" },
{
- :one => {
- :busted => "check",
+ one: {
+ busted: "check",
},
}
)
@@ -294,37 +294,37 @@ describe Chef::Mixin::ParamsValidate do
it "should accept keys that are strings in the options" do
expect do
- @vo.validate({ "one" => "two" }, { :one => { :regex => /^two$/ } })
+ @vo.validate({ "one" => "two" }, { one: { regex: /^two$/ } })
end.not_to raise_error
end
it "should allow an array to kind_of" do
expect do
@vo.validate(
- { :one => "string" },
+ { one: "string" },
{
- :one => {
- :kind_of => [ String, Array ],
+ one: {
+ kind_of: [ String, Array ],
},
}
)
end.not_to raise_error
expect do
@vo.validate(
- { :one => ["string"] },
+ { one: ["string"] },
{
- :one => {
- :kind_of => [ String, Array ],
+ one: {
+ kind_of: [ String, Array ],
},
}
)
end.not_to raise_error
expect do
@vo.validate(
- { :one => Hash.new },
+ { one: Hash.new },
{
- :one => {
- :kind_of => [ String, Array ],
+ one: {
+ kind_of: [ String, Array ],
},
}
)
@@ -333,15 +333,26 @@ 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
+ it "allows a custom validation message" do
+ expect do
+ @vo.validate({ not_blank: "should pass" },
+ { not_blank: { cannot_be: [ :nil, :empty ], validation_message: "my validation message" } })
+ end.not_to raise_error
+ expect do
+ @vo.validate({ not_blank: "" },
+ { not_blank: { cannot_be: [ :nil, :empty ], validation_message: "my validation message" } })
+ end.to raise_error(Chef::Exceptions::ValidationFailed, "my validation message")
+ end
+
it "should set and return a value, then return the same value" do
value = "meow"
expect(@vo.set_or_return(:test, value, {}).object_id).to eq(value.object_id)
@@ -350,38 +361,38 @@ describe Chef::Mixin::ParamsValidate do
it "should set and return a default value when the argument is nil, then return the same value" do
value = "meow"
- expect(@vo.set_or_return(:test, nil, { :default => value }).object_id).to eq(value.object_id)
+ expect(@vo.set_or_return(:test, nil, { default: value }).object_id).to eq(value.object_id)
expect(@vo.set_or_return(:test, nil, {}).object_id).to eq(value.object_id)
end
it "should raise an ArgumentError when argument is nil and required is true" do
expect do
- @vo.set_or_return(:test, nil, { :required => true })
+ @vo.set_or_return(:test, nil, { required: true })
end.to raise_error(ArgumentError)
end
it "should not raise an error when argument is nil and required is false" do
expect do
- @vo.set_or_return(:test, nil, { :required => false })
+ @vo.set_or_return(:test, nil, { required: false })
end.not_to raise_error
end
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(:foo, nil, { :name_attribute => true }).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 })
+ @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 })
+ @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
diff --git a/spec/unit/mixin/powershell_exec_spec.rb b/spec/unit/mixin/powershell_exec_spec.rb
new file mode 100644
index 0000000000..7241e67934
--- /dev/null
+++ b/spec/unit/mixin/powershell_exec_spec.rb
@@ -0,0 +1,43 @@
+#
+# Author:: Stuart Preston (<stuart@chef.io>)
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "chef/mixin/powershell_exec"
+
+describe Chef::Mixin::PowershellExec, :windows_only do
+ let(:powershell_mixin) { Class.new { include Chef::Mixin::PowershellExec } }
+ subject(:object) { powershell_mixin.new }
+
+ describe "#powershell_exec" do
+ it "runs a basic command and returns a Chef::PowerShell object" do
+ expect(object.powershell_exec("$PSVersionTable")).to be_kind_of(Chef::PowerShell)
+ end
+
+ it "runs a command that fails with a non-terminating error and can trap the error via .error?" do
+ execution = object.powershell_exec("this-should-error")
+ expect(execution.error?).to eql(true)
+ end
+
+ it "runs a command that fails with a non-terminating error and can list the errors" do
+ execution = object.powershell_exec("this-should-error")
+ expect(execution.errors).to be_a_kind_of(Array)
+ expect(execution.errors[0]).to be_a_kind_of(String)
+ expect(execution.errors[0]).to include("Runtime exception: this-should-error")
+ end
+ end
+end
diff --git a/spec/unit/mixin/powershell_type_coercions_spec.rb b/spec/unit/mixin/powershell_type_coercions_spec.rb
index 6f52abccfb..210267ba19 100644
--- a/spec/unit/mixin/powershell_type_coercions_spec.rb
+++ b/spec/unit/mixin/powershell_type_coercions_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Jay Mundrawala (<jdm@chef.io>)
-# Copyright:: Copyright 2015-2016, Chef Software, Inc.
+# Copyright:: Copyright 2015-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -34,7 +34,7 @@ describe Chef::Mixin::PowershellTypeCoercions do
["'", '"', "#", "`"].each do |c|
it "base64 encodes a string that contains #{c}" do
- expect(test_class.translate_type("#{c}")).to match(Base64.strict_encode64(c))
+ expect(test_class.translate_type(c.to_s)).to match(Base64.strict_encode64(c))
end
end
@@ -64,14 +64,15 @@ describe Chef::Mixin::PowershellTypeCoercions do
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 })
- expect(test_class.translate_type(test_mash)).to eq("@{a=1;b=1.2;c=$false;d=$true}")
+ node = Chef::Node.new
+ node.default[:test] = { "a" => 1, "b" => 1.2, "c" => false, "d" => true }
+ expect(test_class.translate_type(node[:test])).to eq("@{a=1;b=1.2;c=$false;d=$true}")
end
it "translates a Chef::Node::ImmutableArray like an array" do
- test_array = Chef::Node::ImmutableArray.new([true, false])
- expect(test_class.translate_type(test_array)).to eq("@($true,$false)")
+ node = Chef::Node.new
+ node.default[:test] = [ true, false ]
+ expect(test_class.translate_type(node[:test])).to eq("@($true,$false)")
end
it "falls back :to_psobject if we have not defined at explicit rule" do
diff --git a/spec/unit/mixin/properties_spec.rb b/spec/unit/mixin/properties_spec.rb
index 1af0bc7abd..ee0c252381 100644
--- a/spec/unit/mixin/properties_spec.rb
+++ b/spec/unit/mixin/properties_spec.rb
@@ -11,6 +11,7 @@ module ChefMixinPropertiesSpec
property :a, "a", default: "a"
property :ab, %w{a b}, default: "a"
property :ac, %w{a c}, default: "a"
+ property :d, "d", description: "The d property", introduced: "14.0"
end
context "and a module B with properties b, ab and bc" do
@@ -30,11 +31,20 @@ module ChefMixinPropertiesSpec
end
it "A.properties has a, ab, and ac with types 'a', ['a', 'b'], and ['b', 'c']" do
- expect(A.properties.keys).to eq [ :a, :ab, :ac ]
+ expect(A.properties.keys).to eq [ :a, :ab, :ac, :d ]
expect(A.properties[:a].validation_options[:is]).to eq "a"
expect(A.properties[:ab].validation_options[:is]).to eq %w{a b}
expect(A.properties[:ac].validation_options[:is]).to eq %w{a c}
end
+
+ it "A.properties can get the description of `d`" do
+ expect(A.properties[:d].description).to eq "The d property"
+ end
+
+ it "A.properties can get the release that introduced `d`" do
+ expect(A.properties[:d].introduced).to eq "14.0"
+ end
+
it "B.properties has b, ab, and bc with types 'b', nil and ['b', 'c']" do
expect(B.properties.keys).to eq [ :b, :ab, :bc ]
expect(B.properties[:b].validation_options[:is]).to eq "b"
@@ -42,7 +52,7 @@ module ChefMixinPropertiesSpec
expect(B.properties[:bc].validation_options[:is]).to eq %w{b c}
end
it "C.properties has a, b, c, ac and bc with merged types" do
- expect(C.properties.keys).to eq [ :a, :ab, :ac, :b, :bc, :c ]
+ expect(C.properties.keys).to eq [ :a, :ab, :ac, :d, :b, :bc, :c ]
expect(C.properties[:a].validation_options[:is]).to eq "a"
expect(C.properties[:b].validation_options[:is]).to eq "b"
expect(C.properties[:c].validation_options[:is]).to eq "c"
diff --git a/spec/unit/mixin/securable_spec.rb b/spec/unit/mixin/securable_spec.rb
index 6f50ce853f..de95aa2614 100644
--- a/spec/unit/mixin/securable_spec.rb
+++ b/spec/unit/mixin/securable_spec.rb
@@ -117,10 +117,10 @@ describe Chef::Mixin::Securable do
it "should not accept group/owner names containing embedded carriage returns" do
skip "XXX: params_validate needs to be extended to support multi-line regex"
- #lambda { @securable.group "\ntest" }.should raise_error(ArgumentError)
- #lambda { @securable.group "te\nst" }.should raise_error(ArgumentError)
- #lambda { @securable.owner "\ntest" }.should raise_error(ArgumentError)
- #lambda { @securable.owner "te\nst" }.should raise_error(ArgumentError)
+ # lambda { @securable.group "\ntest" }.should raise_error(ArgumentError)
+ # lambda { @securable.group "te\nst" }.should raise_error(ArgumentError)
+ # lambda { @securable.owner "\ntest" }.should raise_error(ArgumentError)
+ # lambda { @securable.owner "te\nst" }.should raise_error(ArgumentError)
end
it "should accept group/owner names in UTF-8" do
@@ -258,23 +258,23 @@ describe Chef::Mixin::Securable do
end
it "should allow you to specify whether the permissions applies_to_children with true/false/:containers_only/:objects_only" do
- expect { @securable.rights :read, "The Dude", :applies_to_children => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => :containers_only }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => :objects_only }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => "poop" }.to raise_error(ArgumentError)
+ expect { @securable.rights :read, "The Dude", applies_to_children: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: :containers_only }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: :objects_only }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: "poop" }.to raise_error(ArgumentError)
end
it "should allow you to specify whether the permissions applies_to_self with true/false" do
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_self => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_self => "poop" }.to raise_error(ArgumentError)
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, applies_to_self: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_self: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_self: "poop" }.to raise_error(ArgumentError)
end
it "should allow you to specify whether the permissions applies one_level_deep with true/false" do
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => "poop" }.to raise_error(ArgumentError)
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, one_level_deep: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, one_level_deep: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, one_level_deep: "poop" }.to raise_error(ArgumentError)
end
it "should allow multiple rights and deny_rights declarations" do
@@ -288,21 +288,21 @@ describe Chef::Mixin::Securable do
end
it "should allow you to specify whether the permission applies_to_self only if you specified applies_to_children" do
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :applies_to_self => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => false, :applies_to_self => false }.to raise_error(ArgumentError)
- expect { @securable.rights :read, "The Dude", :applies_to_self => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_self => false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, applies_to_self: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, applies_to_self: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: false, applies_to_self: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: false, applies_to_self: false }.to raise_error(ArgumentError)
+ expect { @securable.rights :read, "The Dude", applies_to_self: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_self: false }.not_to raise_error
end
it "should allow you to specify whether the permission applies one_level_deep only if you specified applies_to_children" do
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => true, :one_level_deep => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => true }.to raise_error(ArgumentError)
- expect { @securable.rights :read, "The Dude", :applies_to_children => false, :one_level_deep => false }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :one_level_deep => true }.not_to raise_error
- expect { @securable.rights :read, "The Dude", :one_level_deep => false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, one_level_deep: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: true, one_level_deep: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", applies_to_children: false, one_level_deep: true }.to raise_error(ArgumentError)
+ expect { @securable.rights :read, "The Dude", applies_to_children: false, one_level_deep: false }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", one_level_deep: true }.not_to raise_error
+ expect { @securable.rights :read, "The Dude", one_level_deep: false }.not_to raise_error
end
it "should allow you to specify whether the permissions inherit with true/false" do
diff --git a/spec/unit/mixin/shell_out_spec.rb b/spec/unit/mixin/shell_out_spec.rb
index 9b12969026..7f6021d911 100644
--- a/spec/unit/mixin/shell_out_spec.rb
+++ b/spec/unit/mixin/shell_out_spec.rb
@@ -48,189 +48,403 @@ describe Chef::Mixin::ShellOut do
ENV.update(@original_env)
end
+ let(:retobj) { instance_double(Mixlib::ShellOut, "error!" => false) }
let(:cmd) { "echo '#{rand(1000)}'" }
- describe "#shell_out" do
+ [ :shell_out, :shell_out_compact, :shell_out_compact_timeout, :shell_out!, :shell_out_compact!, :shell_out_compact_timeout! ].each do |method|
+ describe "##{method}" do
+ before do
+ Chef::Config[:treat_deprecation_warnings_as_errors] = false
+ end
- 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
- options = { :environment => { "LC_ALL" => nil, "LANGUAGE" => nil, "LANG" => nil, env_path => nil } }
- expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ 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
+ options = { environment: { "LC_ALL" => nil, "LANGUAGE" => nil, "LANG" => nil, env_path => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
+
+ it "should not change environment language settings when they are set to non-nil" do
+ options = { environment: { "LC_ALL" => "en_US.UTF-8", "LANGUAGE" => "en_US.UTF-8", "LANG" => "en_US.UTF-8", env_path => "foo:bar:baz" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
+
+ it "should set environment language settings to the configured internal locale when they are not present" do
+ options = { environment: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).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],
+ env_path => sanitized_path,
+ },
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
+
+ it "should not mutate the options hash when it adds language settings" do
+ options = { environment: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).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],
+ env_path => sanitized_path,
+ },
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ expect(options[:environment].key?("LC_ALL")).to be false
+ end
end
- it "should not change environment language settings when they are set to non-nil" do
- options = { :environment => { "LC_ALL" => "en_US.UTF-8", "LANGUAGE" => "en_US.UTF-8", "LANG" => "en_US.UTF-8", env_path => "foo:bar:baz" } }
- expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ describe "and env is an option" do
+ it "should not change env when langauge options are set to nil" do
+ options = { env: { "LC_ALL" => nil, "LANG" => nil, "LANGUAGE" => nil, env_path => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ 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", env_path => "foo:bar:baz" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
+
+ it "should set environment language settings to the configured internal locale when they are not present" do
+ options = { env: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).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],
+ env_path => sanitized_path,
+ },
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
+
+ it "should not mutate the options hash when it adds language settings" do
+ options = { env: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).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],
+ env_path => sanitized_path,
+ },
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ expect(options[:env].key?("LC_ALL")).to be false
+ end
end
- 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],
- env_path => sanitized_path,
- },
- }).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ describe "and no env/environment option is present" do
+ it "should set environment language settings to the configured internal locale" do
+ options = { user: "morty" }
+ expect(Chef::Mixin::ShellOut).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],
+ env_path => sanitized_path,
+ },
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd, options)
+ end
end
+ 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",
+ describe "when the last argument is not a Hash" do
+ it "should set environment language settings to the configured internal locale" do
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, {
+ environment: {
"LC_ALL" => Chef::Config[:internal_locale],
"LANG" => Chef::Config[:internal_locale],
"LANGUAGE" => Chef::Config[:internal_locale],
env_path => sanitized_path,
},
- }).and_return(true)
- shell_out_obj.shell_out(cmd, options)
- expect(options[:environment].has_key?("LC_ALL")).to be false
+ }).and_return(retobj)
+ shell_out_obj.send(method, cmd)
end
end
+ end
+ end
- describe "and env is an option" do
- it "should not change env when langauge options are set to nil" do
- options = { :env => { "LC_ALL" => nil, "LANG" => nil, "LANGUAGE" => nil, env_path => nil } }
- expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ describe "#shell_out_with_systems_locale" do
+ before do
+ Chef::Config[:treat_deprecation_warnings_as_errors] = false
+ end
+
+ 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
+ options = { environment: { "LC_ALL" => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
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", env_path => "foo:bar:baz" } }
- expect(shell_out_obj).to receive(:shell_out_command).with(cmd, options).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ it "should not change environment['LC_ALL'] when set to non-nil" do
+ options = { environment: { "LC_ALL" => "en_US.UTF-8" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
end
- 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],
- env_path => sanitized_path,
- },
- }).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ it "should no longer set environment['LC_ALL'] to nil when 'LC_ALL' not present" do
+ options = { environment: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
end
+ 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],
- env_path => sanitized_path,
- },
- }).and_return(true)
- shell_out_obj.shell_out(cmd, options)
- expect(options[:env].has_key?("LC_ALL")).to be false
+ describe "and env is an option" do
+ it "should not change env when set to nil" do
+ options = { env: { "LC_ALL" => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
+ end
+
+ it "should not change env when set to non-nil" do
+ options = { env: { "LC_ALL" => "en_US.UTF-8" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
+ end
+
+ it "should no longer set env['LC_ALL'] to nil when 'LC_ALL' not present" do
+ options = { env: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
end
end
describe "and no env/environment option is present" 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],
- env_path => sanitized_path,
- },
- }).and_return(true)
- shell_out_obj.shell_out(cmd, options)
+ it "should no longer add environment option and set environment['LC_ALL'] to nil" do
+ options = { user: "morty" }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd, options)
end
end
end
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],
- env_path => sanitized_path,
- },
- }).and_return(true)
- shell_out_obj.shell_out(cmd)
+ it "should no longer add environment options and set environment['LC_ALL'] to nil" do
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd).and_return(true)
+ shell_out_obj.shell_out_with_systems_locale(cmd)
end
end
-
end
- describe "#shell_out_with_systems_locale" do
+ describe "#shell_out default_env: false" 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
- options = { :environment => { "LC_ALL" => nil } }
- 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)
+ options = { environment: { "LC_ALL" => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
it "should not change environment['LC_ALL'] when set to non-nil" do
- options = { :environment => { "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)
+ options = { environment: { "LC_ALL" => "en_US.UTF-8" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
it "should no longer set environment['LC_ALL'] to nil when 'LC_ALL' not present" do
- options = { :environment => { "HOME" => "/Users/morty" } }
- 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)
+ options = { environment: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
end
describe "and env is an option" do
it "should not change env when set to nil" do
- options = { :env => { "LC_ALL" => nil } }
- 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)
+ options = { env: { "LC_ALL" => nil } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
it "should not change env when set to non-nil" do
- 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)
+ options = { env: { "LC_ALL" => "en_US.UTF-8" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
it "should no longer set env['LC_ALL'] to nil when 'LC_ALL' not present" do
- options = { :env => { "HOME" => "/Users/morty" } }
- 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)
+ options = { env: { "HOME" => "/Users/morty" } }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
end
describe "and no env/environment option is present" do
it "should no longer add environment option and set environment['LC_ALL'] to nil" do
- options = { :user => "morty" }
- 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)
+ options = { user: "morty" }
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd, options).and_return(true)
+ shell_out_obj.shell_out(cmd, **options, default_env: false)
end
end
end
describe "when the last argument is not a Hash" do
it "should no longer add environment options and set environment['LC_ALL'] to nil" do
- expect(shell_out_obj).to receive(:shell_out_command).with(cmd).and_return(true)
- shell_out_obj.shell_out_with_systems_locale(cmd)
+ expect(Chef::Mixin::ShellOut).to receive(:shell_out_command).with(cmd).and_return(true)
+ shell_out_obj.shell_out(cmd, default_env: false)
+ end
+ end
+ end
+
+ describe "deprecations" do
+ [ :shell_out_with_systems_locale, :shell_out_compact, :shell_out_compact_timeout, :shell_out_with_systems_locale!, :shell_out_compact!, :shell_out_compact_timeout! ].each do |method|
+ it "should not respond to #{method} in Chef-15", chef: ">= 15" do
+ expect(shell_out_obj.respond_to?(method)).to be false
+ end
+ end
+
+ it "removed shell_out_with_timeout from Chef::Provider::Package", chef: ">= 15" do
+ expect(Chef::Provider::Package.instance_methods + Chef::Provider::Package.private_instance_methods).not_to include(:shell_out_with_timeout)
+ end
+
+ it "removed shell_out_with_timeout! from Chef::Provider::Package", chef: ">= 15" do
+ expect(Chef::Provider::Package.instance_methods + Chef::Provider::Package.private_instance_methods).not_to include(:shell_out_with_timeout!)
+ end
+ end
+
+ describe "Custom Resource timeouts" do
+ class CustomResource < Chef::Resource
+ provides :whatever
+
+ property :timeout, Numeric
+
+ action :install do
+ end
+ end
+
+ let(:new_resource) { CustomResource.new("foo") }
+ let(:provider) { new_resource.provider_for_action(:install) }
+
+ describe "on Chef-14", chef: "< 15" do
+ it "doesn't add timeout for shell_out" do
+ expect(provider).to receive(:shell_out_compacted).with("foo")
+ provider.shell_out("foo")
+ end
+ it "doesn't add timeout for shell_out!" do
+ expect(provider).to receive(:shell_out_compacted!).with("foo")
+ provider.shell_out!("foo")
+ end
+ end
+
+ describe "on Chef-15", chef: ">= 15" do
+ [ :shell_out, :shell_out! ].each do |method|
+ stubbed_method = (method == :shell_out) ? :shell_out_compacted : :shell_out_compacted!
+ it "#{method} defaults to 900 seconds" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 900)
+ provider.send(method, "foo")
+ end
+ it "#{method} overrides the default timeout with its options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} defaults to 900 seconds and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", env: nil, timeout: 900)
+ provider.send(method, "foo", env: nil)
+ end
+ it "#{method} overrides the default timeout with its options and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option and preseves options" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
+ end
+ end
+ end
+ end
+
+ describe "timeouts" do
+ let(:new_resource) { Chef::Resource::Package.new("foo") }
+ let(:provider) { new_resource.provider_for_action(:install) }
+
+ [ :shell_out, :shell_out! ].each do |method|
+ stubbed_method = (method == :shell_out) ? :shell_out_compacted : :shell_out_compacted!
+ it "#{method} defaults to 900 seconds" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 900)
+ provider.send(method, "foo")
+ end
+ it "#{method} overrides the default timeout with its options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} defaults to 900 seconds and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", env: nil, timeout: 900)
+ provider.send(method, "foo", env: nil)
+ end
+ it "#{method} overrides the default timeout with its options and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option and preseves options" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
end
end
end
+ describe "deprecated timeouts" do # Chef 15: delete me
+ let(:new_resource) { Chef::Resource::Package.new("foo") }
+ let(:provider) { new_resource.provider_for_action(:install) }
+
+ before(:each) do
+ Chef::Config[:treat_deprecation_warnings_as_errors] = false
+ end
+
+ [ :shell_out_compact_timeout, :shell_out_compact_timeout! ].each do |method|
+ stubbed_method = (method == :shell_out_compact_timeout) ? :shell_out_compacted : :shell_out_compacted!
+ it "#{method} defaults to 900 seconds" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 900)
+ provider.send(method, "foo")
+ end
+ it "#{method} overrides the default timeout with its options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 99)
+ provider.send(method, "foo", timeout: 1)
+ end
+ it "#{method} defaults to 900 seconds and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", env: nil, timeout: 900)
+ provider.send(method, "foo", env: nil)
+ end
+ it "#{method} overrides the default timeout with its options and preserves options" do
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 1, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
+ end
+ it "#{method} overrides the new_resource.timeout with the timeout option and preseves options" do
+ new_resource.timeout(99)
+ expect(provider).to receive(stubbed_method).with("foo", timeout: 99, env: nil)
+ provider.send(method, "foo", timeout: 1, env: nil)
+ end
+ end
+ end
end
end
diff --git a/spec/unit/mixin/user_context_spec.rb b/spec/unit/mixin/user_context_spec.rb
index f2119b6dbc..896241f173 100644
--- a/spec/unit/mixin/user_context_spec.rb
+++ b/spec/unit/mixin/user_context_spec.rb
@@ -41,10 +41,9 @@ describe "a class that mixes in user_context" do
before do
allow(::Chef::Platform).to receive(:windows?).and_return(true)
allow(::Chef::Util::Windows::LogonSession).to receive(:new).and_return(logon_session)
- allow(instance_with_user_context).to receive(:node).and_return({ "platform_family" => "windows" })
end
- let(:logon_session) { instance_double("::Chef::Util::Windows::LogonSession", :set_user_context => nil, :open => nil, :close => nil) }
+ let(:logon_session) { instance_double("::Chef::Util::Windows::LogonSession", set_user_context: nil, open: nil, close: nil) }
it "does not raise an exception when the user and all parameters are nil" do
expect { instance_with_user_context.with_context(nil, nil, nil) {} }.not_to raise_error
@@ -99,7 +98,7 @@ describe "a class that mixes in user_context" do
context "when not running on Windows" do
before do
- allow(instance_with_user_context).to receive(:node).and_return({ "platform_family" => "ubuntu" })
+ allow(::Chef::Platform).to receive(:windows?).and_return(false)
end
it "raises a ::Chef::Exceptions::UnsupportedPlatform exception" do
diff --git a/spec/unit/mixin/xml_escape_spec.rb b/spec/unit/mixin/xml_escape_spec.rb
index 495ad0662c..761cab60c8 100644
--- a/spec/unit/mixin/xml_escape_spec.rb
+++ b/spec/unit/mixin/xml_escape_spec.rb
@@ -49,6 +49,6 @@ describe Chef::Mixin::XMLEscape do
end
it "converts win 1252 characters correctly" do
- expect(@escaper.xml_escape("#{0x80.chr}")).to eq("&#8364;")
+ expect(@escaper.xml_escape((0x80.chr).to_s)).to eq("&#8364;")
end
end
diff --git a/spec/unit/node/attribute_spec.rb b/spec/unit/node/attribute_spec.rb
index cf8d4d4a4f..36827215f0 100644
--- a/spec/unit/node/attribute_spec.rb
+++ b/spec/unit/node/attribute_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: AJ Christensen (<aj@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,8 +22,8 @@ require "chef/node/attribute"
describe Chef::Node::Attribute do
let(:events) { instance_double(Chef::EventDispatch::Dispatcher) }
- let(:run_context) { instance_double(Chef::RunContext, :events => events) }
- let(:node) { instance_double(Chef::Node, :run_context => run_context) }
+ let(:run_context) { instance_double(Chef::RunContext, events: events) }
+ let(:node) { instance_double(Chef::Node, run_context: run_context) }
before(:each) do
allow(events).to receive(:attribute_changed)
@attribute_hash =
@@ -184,7 +184,7 @@ describe Chef::Node::Attribute do
[ :normal, :default, :override, :automatic ].each do |accessor|
it "should set #{accessor}" do
- na = Chef::Node::Attribute.new({ :normal => true }, { :default => true }, { :override => true }, { :automatic => true })
+ na = Chef::Node::Attribute.new({ normal: true }, { default: true }, { override: true }, { automatic: true })
expect(na.send(accessor)).to eq({ accessor.to_s => true })
end
end
@@ -522,20 +522,20 @@ describe Chef::Node::Attribute do
describe "has_key?" do
it "should return true if an attribute exists" do
- expect(@attributes.has_key?("music")).to eq(true)
+ expect(@attributes.key?("music")).to eq(true)
end
it "should return false if an attribute does not exist" do
- expect(@attributes.has_key?("ninja")).to eq(false)
+ expect(@attributes.key?("ninja")).to eq(false)
end
it "should return false if an attribute does not exist using dot notation" do
- expect(@attributes.has_key?("does_not_exist_at_all")).to eq(false)
+ expect(@attributes.key?("does_not_exist_at_all")).to eq(false)
end
it "should return true if an attribute exists but is set to false" do
- @attributes.has_key?("music")
- expect(@attributes["music"].has_key?("apophis")).to eq(true)
+ @attributes.key?("music")
+ expect(@attributes["music"].key?("apophis")).to eq(true)
end
it "does not find keys above the current nesting level" do
@@ -590,7 +590,7 @@ describe Chef::Node::Attribute do
it "should yield each top level key" do
collect = Array.new
- @attributes.keys.each do |k|
+ @attributes.each_key do |k|
collect << k
end
expect(collect.include?("one")).to eq(true)
@@ -603,7 +603,7 @@ describe Chef::Node::Attribute do
it "should yield lower if we go deeper" do
collect = Array.new
- @attributes["one"].keys.each do |k|
+ @attributes["one"].each_key do |k|
collect << k
end
expect(collect.include?("two")).to eq(true)
@@ -886,11 +886,11 @@ describe Chef::Node::Attribute do
end
it "should return true if any key has the value supplied" do
- expect(@attributes.has_value?("cookies")).to eq(true)
+ expect(@attributes.value?("cookies")).to eq(true)
end
it "should return false no key has the value supplied" do
- expect(@attributes.has_value?("lololol")).to eq(false)
+ expect(@attributes.value?("lololol")).to eq(false)
end
it "should alias value?" do
diff --git a/spec/unit/node/immutable_collections_spec.rb b/spec/unit/node/immutable_collections_spec.rb
index 2d3392041c..273c3d2704 100644
--- a/spec/unit/node/immutable_collections_spec.rb
+++ b/spec/unit/node/immutable_collections_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2012-2017, Chef Software Inc.
+# Copyright:: Copyright 2012-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,6 +29,11 @@ describe Chef::Node::ImmutableMash do
@immutable_mash = Chef::Node::ImmutableMash.new(@data_in)
end
+ it "does not have any unaudited methods" do
+ unaudited_methods = Hash.instance_methods - Object.instance_methods - Chef::Node::Mixin::ImmutablizeHash::DISALLOWED_MUTATOR_METHODS - Chef::Node::Mixin::ImmutablizeHash::ALLOWED_METHODS
+ expect(unaudited_methods).to be_empty
+ end
+
it "element references like regular hash" do
expect(@immutable_mash[:top][:second_level]).to eq("some value")
end
@@ -221,6 +226,11 @@ describe Chef::Node::ImmutableArray do
end
end
+ it "does not have any unaudited methods" do
+ unaudited_methods = Array.instance_methods - Object.instance_methods - Chef::Node::Mixin::ImmutablizeArray::DISALLOWED_MUTATOR_METHODS - Chef::Node::Mixin::ImmutablizeArray::ALLOWED_METHODS
+ expect(unaudited_methods).to be_empty
+ end
+
it "can be duped even if some elements can't" do
@immutable_array.dup
end
diff --git a/spec/unit/node/vivid_mash_spec.rb b/spec/unit/node/vivid_mash_spec.rb
index 4898c22380..e1021ba0c0 100644
--- a/spec/unit/node/vivid_mash_spec.rb
+++ b/spec/unit/node/vivid_mash_spec.rb
@@ -61,7 +61,7 @@ describe Chef::Node::VividMash do
it "deep converts values through arrays" do
expect(root).to receive(:reset_cache).with("foo")
- vivid["foo"] = [ { :bar => true } ]
+ vivid["foo"] = [ { bar: true } ]
expect(vivid["foo"].class).to eql(Chef::Node::AttrArray)
expect(vivid["foo"][0].class).to eql(Chef::Node::VividMash)
expect(vivid["foo"][0]["bar"]).to be true
@@ -69,7 +69,7 @@ describe Chef::Node::VividMash do
it "deep converts values through nested arrays" do
expect(root).to receive(:reset_cache).with("foo")
- vivid["foo"] = [ [ { :bar => true } ] ]
+ vivid["foo"] = [ [ { bar: true } ] ]
expect(vivid["foo"].class).to eql(Chef::Node::AttrArray)
expect(vivid["foo"][0].class).to eql(Chef::Node::AttrArray)
expect(vivid["foo"][0][0].class).to eql(Chef::Node::VividMash)
@@ -78,7 +78,7 @@ describe Chef::Node::VividMash do
it "deep converts values through hashes" do
expect(root).to receive(:reset_cache).with("foo")
- vivid["foo"] = { baz: { :bar => true } }
+ vivid["foo"] = { baz: { bar: true } }
expect(vivid["foo"]).to be_an_instance_of(Chef::Node::VividMash)
expect(vivid["foo"]["baz"]).to be_an_instance_of(Chef::Node::VividMash)
expect(vivid["foo"]["baz"]["bar"]).to be true
diff --git a/spec/unit/node_map_spec.rb b/spec/unit/node_map_spec.rb
index 822f689eab..df70ad380a 100644
--- a/spec/unit/node_map_spec.rb
+++ b/spec/unit/node_map_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Lamont Granquist (<lamont@chef.io>)
-# Copyright:: Copyright 2014-2017, Chef Software Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,6 +19,15 @@
require "spec_helper"
require "chef/node_map"
+class Foo; end
+class Bar; end
+
+class FooResource < Chef::Resource; end
+class BarResource < Chef::Resource; end
+
+class FooProvider < Chef::Provider; end
+class BarProvider < Chef::Provider; end
+
describe Chef::NodeMap do
let(:node_map) { Chef::NodeMap.new }
@@ -101,6 +110,62 @@ describe Chef::NodeMap do
end
end
+ describe "platform version checks" do
+ before do
+ node_map.set(:thing, :foo, platform_family: "rhel", platform_version: ">= 7")
+ end
+
+ it "handles non-x.y.z platform versions without throwing an exception" do
+ allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
+ allow(node).to receive(:[]).with(:platform_version).and_return("7.19.2.2F")
+ expect(node_map.get(node, :thing)).to eql(:foo)
+ end
+
+ it "handles non-x.y.z platform versions without throwing an exception when the match fails" do
+ allow(node).to receive(:[]).with(:platform_family).and_return("rhel")
+ allow(node).to receive(:[]).with(:platform_version).and_return("4.19.2.2F")
+ expect(node_map.get(node, :thing)).to eql(nil)
+ end
+ end
+
+ describe "ordering classes" do
+ it "last writer wins when its reverse alphabetic order" do
+ node_map.set(:thing, Foo)
+ node_map.set(:thing, Bar)
+ expect(node_map.get(node, :thing)).to eql(Bar)
+ end
+
+ it "last writer wins when its alphabetic order" do
+ node_map.set(:thing, Bar)
+ node_map.set(:thing, Foo)
+ expect(node_map.get(node, :thing)).to eql(Foo)
+ end
+ end
+
+ describe "deleting classes" do
+ it "deletes a class and removes the mapping completely" do
+ node_map.set(:thing, Bar)
+ expect( node_map.delete_class(Bar) ).to include({ thing: [{ klass: Bar, cookbook_override: false, core_override: false }] })
+ expect( node_map.get(node, :thing) ).to eql(nil)
+ end
+
+ it "deletes a class and leaves the mapping that still has an entry" do
+ node_map.set(:thing, Bar)
+ node_map.set(:thing, Foo)
+ expect( node_map.delete_class(Bar) ).to eql({ thing: [{ klass: Bar, cookbook_override: false, core_override: false }] })
+ expect( node_map.get(node, :thing) ).to eql(Foo)
+ end
+
+ it "handles deleting classes from multiple keys" do
+ node_map.set(:thing1, Bar)
+ node_map.set(:thing2, Bar)
+ node_map.set(:thing2, Foo)
+ expect( node_map.delete_class(Bar) ).to eql({ thing1: [{ klass: Bar, cookbook_override: false, core_override: false }], thing2: [{ klass: Bar, cookbook_override: false, core_override: false }] })
+ expect( node_map.get(node, :thing1) ).to eql(nil)
+ expect( node_map.get(node, :thing2) ).to eql(Foo)
+ end
+ end
+
describe "with a block doing platform_version checks" do
before do
node_map.set(:thing, :foo, platform_family: "rhel") do |node|
@@ -145,4 +210,66 @@ describe Chef::NodeMap do
end
end
+ describe "locked mode" do
+ context "while unlocked" do
+ it "allows setting the same key twice" do
+ expect(Chef).to_not receive(:deprecated)
+ node_map.set(:foo, FooResource)
+ node_map.set(:foo, BarResource)
+ expect(node_map.get(node, :foo)).to eql(BarResource)
+ end
+ end
+
+ context "while locked" do
+ # Uncomment the commented `expect`s in 15.0.
+ it "rejects setting the same key twice" do
+ expect(Chef).to receive(:deprecated).with(:map_collision, /resource foo/)
+ node_map.set(:foo, FooResource)
+ node_map.lock!
+ node_map.set(:foo, BarResource)
+ # expect(node_map.get(node, :foo)).to eql(FooResource)
+ end
+
+ it "allows setting the same key twice when the first has allow_cookbook_override" do
+ expect(Chef).to_not receive(:deprecated)
+ node_map.set(:foo, FooResource, allow_cookbook_override: true)
+ node_map.lock!
+ node_map.set(:foo, BarResource)
+ expect(node_map.get(node, :foo)).to eql(BarResource)
+ end
+
+ it "allows setting the same key twice when the first has allow_cookbook_override with a future version" do
+ expect(Chef).to_not receive(:deprecated)
+ node_map.set(:foo, FooResource, allow_cookbook_override: "< 100")
+ node_map.lock!
+ node_map.set(:foo, BarResource)
+ expect(node_map.get(node, :foo)).to eql(BarResource)
+ end
+
+ it "rejects setting the same key twice when the first has allow_cookbook_override with a past version" do
+ expect(Chef).to receive(:deprecated).with(:map_collision, /resource foo/)
+ node_map.set(:foo, FooResource, allow_cookbook_override: "< 1")
+ node_map.lock!
+ node_map.set(:foo, BarResource)
+ # expect(node_map.get(node, :foo)).to eql(FooResource)
+ end
+
+ it "allows setting the same key twice when the second has __core_override__" do
+ expect(Chef).to_not receive(:deprecated)
+ node_map.set(:foo, FooResource)
+ node_map.lock!
+ node_map.set(:foo, BarResource, __core_override__: true)
+ expect(node_map.get(node, :foo)).to eql(BarResource)
+ end
+
+ it "rejects setting the same key twice for a provider" do
+ expect(Chef).to receive(:deprecated).with(:map_collision, /provider foo/)
+ node_map.set(:foo, FooProvider)
+ node_map.lock!
+ node_map.set(:foo, BarProvider)
+ # expect(node_map.get(node, :foo)).to eql(FooProvider)
+ end
+ end
+ end
+
end
diff --git a/spec/unit/node_spec.rb b/spec/unit/node_spec.rb
index 7dc972b5a0..0ca5f83adc 100644
--- a/spec/unit/node_spec.rb
+++ b/spec/unit/node_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -52,7 +52,7 @@ describe Chef::Node do
describe "when the node does not exist on the server" do
before do
- response = OpenStruct.new(:code => "404")
+ response = OpenStruct.new(code: "404")
exception = Net::HTTPServerException.new("404 not found", response)
allow(Chef::Node).to receive(:load).and_raise(exception)
node.name("created-node")
@@ -186,7 +186,7 @@ describe Chef::Node do
expect { node.policy_group = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqurstuvwxyz0123456789-_:." }.to_not raise_error
end
- it "sets an environment with chef_environment(something)" do
+ it "sets a policy_group with policy_group(something)" do
node.policy_group("staging")
expect(node.policy_group).to eq("staging")
end
@@ -303,20 +303,6 @@ describe Chef::Node do
expect(node["tags"]).to eq(%w{one two three four})
end
- it "set is a deprecated alias for normal" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- expect(Chef).to receive(:deprecated).with(:attributes, /set is deprecated/)
- node.set[:snoopy][:is_a_puppy] = true
- expect(node.normal[:snoopy][:is_a_puppy]).to eq(true)
- end
-
- it "set_unless is a deprecated alias for normal_unless" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- expect(Chef).to receive(:deprecated).with(:attributes, /set_unless is deprecated/)
- node.set_unless[:snoopy][:is_a_puppy] = false
- expect(node.normal[:snoopy][:is_a_puppy]).to eq(false)
- end
-
it "normal_unless sets a value even if default or override attrs are set" do
node.default[:decontamination] = true
node.override[:decontamination] = false
@@ -866,7 +852,7 @@ describe Chef::Node do
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
@@ -958,7 +944,7 @@ describe Chef::Node do
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
@@ -967,6 +953,14 @@ describe Chef::Node do
expect(node.automatic_attrs[:platform_version]).to eq("23.42")
end
+ it "sets the chef guid attribute correctly" do
+ guid = Chef::Config[:chef_guid]
+ Chef::Config[:chef_guid] = "test-guid-guid"
+ node.consume_external_attrs(@ohai_data, {})
+ expect(node.automatic_attrs[:chef_guid]).to eq("test-guid-guid")
+ Chef::Config[:chef_guid] = guid
+ end
+
it "consumes the run list from provided json attributes" do
node.consume_external_attrs(@ohai_data, { "run_list" => ["recipe[unicorn]"] })
expect(node.run_list).to eq(["recipe[unicorn]"])
@@ -1102,12 +1096,12 @@ describe Chef::Node 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
@@ -1166,16 +1160,16 @@ describe Chef::Node do
describe "roles" do
it "should allow you to query whether or not it has a recipe applied with role?" do
- node.run_list << "role[sunrise]"
+ node.automatic["roles"] = %w{sunrise}
expect(node.role?("sunrise")).to eql(true)
expect(node.role?("not at home")).to eql(false)
end
it "should allow you to set roles with arguments" do
- node.run_list << "role[one]"
- node.run_list << "role[two]"
+ node.automatic["roles"] = %w{one two}
expect(node.role?("one")).to eql(true)
expect(node.role?("two")).to eql(true)
+ expect(node.role?("three")).to eql(false)
end
end
@@ -1275,7 +1269,7 @@ describe Chef::Node do
end
describe "converting to or from json" do
- it "should serialize itself as json", :json => true do
+ it "should serialize itself as json", json: true do
node.from_file(File.expand_path("nodes/test.example.com.rb", CHEF_SPEC_DATA))
json = Chef::JSONCompat.to_json(node)
expect(json).to match(/json_class/)
@@ -1287,16 +1281,16 @@ describe Chef::Node do
expect(json).to match(/run_list/)
end
- 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
+ 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" }
json = Chef::JSONCompat.to_json(node)
expect(json).to match(/\"run_list\":\[\"role\[Cthulu\]\",\"role\[Hastur\]\"\]/)
end
- it "should serialize the correct run list", :json => true do
+ it "should serialize the correct run list", json: true do
node.run_list << "role[marxist]"
node.run_list << "role[leninist]"
node.override_runlist << "role[stalinist]"
@@ -1321,7 +1315,7 @@ describe Chef::Node do
expect(node_for_json["default"]["env default"]).to eq("env default")
end
- it "should deserialize itself from json", :json => true do
+ it "should deserialize itself from json", json: true do
node.from_file(File.expand_path("nodes/test.example.com.rb", CHEF_SPEC_DATA))
json = Chef::JSONCompat.to_json(node)
serialized_node = Chef::Node.from_hash(Chef::JSONCompat.parse(json))
@@ -1367,6 +1361,7 @@ describe Chef::Node do
expect(round_tripped_node.policy_name).to eq("my-application")
expect(round_tripped_node.policy_group).to eq("staging")
+ expect(round_tripped_node.chef_environment).to eq("staging")
end
end
@@ -1397,7 +1392,7 @@ describe Chef::Node do
describe "list" do
describe "inflated" do
it "should return a hash of node names and objects" do
- n1 = double("Chef::Node", :name => "one")
+ n1 = double("Chef::Node", name: "one")
allow(n1).to receive(:kind_of?).with(Chef::Node) { true }
expect(@query).to receive(:search).with(:node).and_yield(n1)
r = Chef::Node.list(true)
@@ -1451,7 +1446,7 @@ describe Chef::Node do
it "should create if it cannot update" do
node.name("monkey")
allow(node).to receive(:data_for_save).and_return({})
- exception = double("404 error", :code => "404")
+ exception = double("404 error", code: "404")
expect(@rest).to receive(:put).and_raise(Net::HTTPServerException.new("foo", exception))
expect(@rest).to receive(:post).with("nodes", {})
node.save
diff --git a/spec/unit/org_spec.rb b/spec/unit/org_spec.rb
index 49557417a5..79a29b1fff 100644
--- a/spec/unit/org_spec.rb
+++ b/spec/unit/org_spec.rb
@@ -164,7 +164,7 @@ 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
@@ -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 aa2b3c1f11..82ed4de9c6 100644
--- a/spec/unit/platform/query_helpers_spec.rb
+++ b/spec/unit/platform/query_helpers_spec.rb
@@ -18,19 +18,6 @@
require "spec_helper"
-describe "Chef::Platform#windows_server_2003?" do
- it "returns false early when not on windows" do
- allow(ChefConfig).to receive(:windows?).and_return(false)
- expect(Chef::Platform).not_to receive(:require)
- expect(Chef::Platform.windows_server_2003?).to be_falsey
- end
-
- # CHEF-4888: Need to call WIN32OLE.ole_initialize in new threads
- it "does not raise an exception" do
- expect { Thread.fork { Chef::Platform.windows_server_2003? }.join }.not_to raise_error
- end
-end
-
describe "Chef::Platform#windows_nano_server?" do
include_context "Win32"
@@ -64,9 +51,9 @@ describe "Chef::Platform#windows_nano_server?" do
it "returns true when the registry value is 1" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_yield(registry)
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_yield(registry)
expect(registry).to receive(:[]).with("NanoServer").and_return(1)
expect(Chef::Platform.windows_nano_server?).to be true
end
@@ -74,9 +61,9 @@ describe "Chef::Platform#windows_nano_server?" do
it "returns false when the registry value is not 1" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_yield(registry)
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_yield(registry)
expect(registry).to receive(:[]).with("NanoServer").and_return(0)
expect(Chef::Platform.windows_nano_server?).to be false
end
@@ -84,20 +71,20 @@ describe "Chef::Platform#windows_nano_server?" do
it "returns false when the registry value does not exist" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_yield(registry)
- expect(registry).to receive(:[]).with("NanoServer").
- and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_yield(registry)
+ expect(registry).to receive(:[]).with("NanoServer")
+ .and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
expect(Chef::Platform.windows_nano_server?).to be false
end
it "returns false when the registry key does not exist" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
expect(Chef::Platform.windows_nano_server?).to be false
end
end
@@ -135,18 +122,18 @@ describe "Chef::Platform#supports_msi?" do
it "returns true when the registry key exists" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_yield(registry)
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_yield(registry)
expect(Chef::Platform.supports_msi?).to be true
end
it "returns false when the registry key does not exist" do
allow(ChefConfig).to receive(:windows?).and_return(true)
allow(Chef::Platform).to receive(:require).with("win32/registry")
- expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open).
- with(key, access).
- and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
+ expect(Win32::Registry::HKEY_LOCAL_MACHINE).to receive(:open)
+ .with(key, access)
+ .and_raise(Win32::Registry::Error, "The system cannot find the file specified.")
expect(Chef::Platform.supports_msi?).to be false
end
end
@@ -201,18 +188,18 @@ describe "Chef::Platform#dsc_refresh_mode_disabled?" do
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).
- with(node, "Get-DscLocalConfigurationManager", :object).
- and_return(cmdlet)
+ expect(Chef::Util::Powershell::Cmdlet).to receive(:new)
+ .with(node, "Get-DscLocalConfigurationManager", :object)
+ .and_return(cmdlet)
expect(cmdlet).to receive(:run!).and_return(cmdlet_result)
expect(cmdlet_result).to receive(:return_value).and_return({ "RefreshMode" => "Disabled" })
expect(Chef::Platform.dsc_refresh_mode_disabled?(node)).to be true
end
it "returns false when RefreshMode is not Disabled" do
- expect(Chef::Util::Powershell::Cmdlet).to receive(:new).
- with(node, "Get-DscLocalConfigurationManager", :object).
- and_return(cmdlet)
+ expect(Chef::Util::Powershell::Cmdlet).to receive(:new)
+ .with(node, "Get-DscLocalConfigurationManager", :object)
+ .and_return(cmdlet)
expect(cmdlet).to receive(:run!).and_return(cmdlet_result)
expect(cmdlet_result).to receive(:return_value).and_return({ "RefreshMode" => "LaLaLa" })
expect(Chef::Platform.dsc_refresh_mode_disabled?(node)).to be false
diff --git a/spec/unit/policy_builder/expand_node_object_spec.rb b/spec/unit/policy_builder/expand_node_object_spec.rb
index a7f4f1fa43..122c960c11 100644
--- a/spec/unit/policy_builder/expand_node_object_spec.rb
+++ b/spec/unit/policy_builder/expand_node_object_spec.rb
@@ -48,7 +48,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do
it "implements a setup_run_context method that accepts a list of recipe files to run" do
expect(policy_builder).to respond_to(:setup_run_context)
- expect(policy_builder.method(:setup_run_context).arity).to eq(-1) #optional argument
+ expect(policy_builder.method(:setup_run_context).arity).to eq(-1) # optional argument
end
it "implements a run_context method" do
@@ -176,7 +176,7 @@ describe Chef::PolicyBuilder::ExpandNodeObject do
let(:expansion) do
recipe_list = Chef::RunList::VersionedRecipeList.new
recipe_list.add_recipe("recipe[from_role::default", "1.0.2")
- double("RunListExpansion", :recipes => recipe_list)
+ double("RunListExpansion", recipes: recipe_list)
end
let(:node) do
@@ -268,13 +268,13 @@ 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
# will have object equality rather than semantic equality #== semantics).
let(:cookbook_hash) { double("cookbook hash") }
- let(:expanded_cookbook_hash) { double("expanded cookbook hash", :each => nil) }
+ let(:expanded_cookbook_hash) { double("expanded cookbook hash", each: nil) }
let(:cookbook_synchronizer) { double("CookbookSynchronizer") }
diff --git a/spec/unit/policy_builder/policyfile_spec.rb b/spec/unit/policy_builder/policyfile_spec.rb
index 466d0f970b..ab2fdecfe7 100644
--- a/spec/unit/policy_builder/policyfile_spec.rb
+++ b/spec/unit/policy_builder/policyfile_spec.rb
@@ -70,8 +70,44 @@ 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) do
+ {
+ "policyfile_default_attr" => "policyfile_default_value",
+ "top_level_attr" => "hat",
+ "baseline_attr" => {
+ "one" => 1,
+ "two" => 2,
+ "deep" => {
+ "three" => 3,
+ "four" => [4],
+ "five" => [5],
+ },
+ },
+ "policy_group_value" => {
+ "baseline_attr" => {
+ "one" => 111,
+ },
+ },
+ }
+ end
+
+ let(:policyfile_override_attributes) do
+ {
+ "policyfile_override_attr" => "policyfile_override_value",
+ "baseline_attr" => {
+ "deep" => {
+ "three" => 333 },
+ },
+ "policy_group_value" => {
+ "top_level_attr" => "cat",
+ "baseline_attr" => {
+ "deep" => {
+ "four" => [444],
+ },
+ },
+ },
+ }
+ end
let(:policyfile_run_list) { ["recipe[example1::default]", "recipe[example2::server]"] }
@@ -185,9 +221,9 @@ describe Chef::PolicyBuilder::Policyfile do
let(:error404) { Net::HTTPServerException.new("404 message", :body) }
before do
- expect(api_service).to receive(:get).
- with("data/policyfiles/example-policy-stage").
- and_raise(error404)
+ expect(api_service).to receive(:get)
+ .with("data/policyfiles/example-policy-stage")
+ .and_raise(error404)
end
it "raises an error" do
@@ -357,10 +393,10 @@ describe Chef::PolicyBuilder::Policyfile do
let(:run_list_for_data_collector) do
{
- :id => "_policy_node",
- :run_list => [
- { :type => "recipe", :name => "test::default", :skipped => false, :version => nil },
- { :type => "recipe", :name => "test::other", :skipped => false, :version => nil },
+ id: "_policy_node",
+ run_list: [
+ { type: "recipe", name: "test::default", skipped: false, version: nil },
+ { type: "recipe", name: "test::other", skipped: false, version: nil },
],
}
end
@@ -538,6 +574,10 @@ describe Chef::PolicyBuilder::Policyfile do
expect(Chef::Config[:policy_group]).to eq("policy_group_from_node_json")
expect(node.policy_name).to eq("policy_name_from_node_json")
expect(node.policy_group).to eq("policy_group_from_node_json")
+ expect(node.automatic_attrs[:policy_name]).to eq("policy_name_from_node_json")
+ expect(node.automatic_attrs[:policy_group]).to eq("policy_group_from_node_json")
+ expect(node.automatic_attrs[:chef_environment]).to eq("policy_group_from_node_json")
+
end
end
@@ -587,6 +627,7 @@ describe Chef::PolicyBuilder::Policyfile do
it "create node.automatic_attrs[:recipes]" do
expect(node.automatic_attrs[:recipes]).to eq(["example1::default", "example2::server"])
end
+
end
context "when a named run_list is given" do
@@ -636,6 +677,42 @@ describe Chef::PolicyBuilder::Policyfile do
end
end
+
+ describe "hoisting attribute values" do
+ context "with no policy group set" do
+ it "does not hoist policy_group specific attributes" do
+ expect( node["top_level_attr"] ).to eql("hat")
+ expect( node["baseline_attr"]["one"] ).to eql(1)
+ expect( node["baseline_attr"]["two"] ).to eql(2)
+ expect( node["baseline_attr"]["deep"]["three"] ).to eql(333)
+ expect( node["baseline_attr"]["deep"]["four"] ).to eql([4])
+ expect( node["baseline_attr"]["deep"]["five"] ).to eql([5])
+ end
+ end
+
+ context "with a policy group set" do
+ before do
+ Chef::Config[:policy_group] = "policy_group_value"
+ policy_builder.finish_load_node(node)
+ policy_builder.build_node
+ end
+
+ it "hoists default attributes" do
+ expect( node["top_level_attr"] ).to eql("cat")
+ expect( node["baseline_attr"]["one"]).to eql(111)
+ expect( node["baseline_attr"]["two"] ).to eql(2)
+ expect( node["baseline_attr"]["deep"]["five"] ).to eql([5])
+ end
+
+ it "hoists override attributes" do
+ expect( node["top_level_attr"] ).to eql("cat")
+ expect( node["baseline_attr"]["two"] ).to eql(2)
+ expect( node["baseline_attr"]["deep"]["three"] ).to eql(333)
+ expect( node["baseline_attr"]["deep"]["four"] ).to eql([444])
+ expect( node["baseline_attr"]["deep"]["five"] ).to eql([5])
+ end
+ end
+ end
end
describe "fetching the desired cookbook set" do
@@ -667,8 +744,8 @@ describe Chef::PolicyBuilder::Policyfile do
policy_builder.finish_load_node(node)
policy_builder.build_node
- expect(api_service).to receive(:get).with(cookbook1_url).
- and_raise(error404)
+ expect(api_service).to receive(:get).with(cookbook1_url)
+ .and_raise(error404)
end
it "raises an error indicating which cookbook is missing" do
@@ -686,9 +763,9 @@ describe Chef::PolicyBuilder::Policyfile do
policy_builder.finish_load_node(node)
policy_builder.build_node
- allow(Chef::CookbookSynchronizer).to receive(:new).
- with(expected_cookbook_hash, events).
- and_return(cookbook_synchronizer)
+ allow(Chef::CookbookSynchronizer).to receive(:new)
+ .with(expected_cookbook_hash, events)
+ .and_return(cookbook_synchronizer)
end
after do
@@ -737,15 +814,15 @@ describe Chef::PolicyBuilder::Policyfile do
context "when the cookbooks exist on the server" do
before do
- expect(api_service).to receive(:get).with(cookbook1_url).
- and_return(example1_cookbook_data)
- expect(api_service).to receive(:get).with(cookbook2_url).
- and_return(example2_cookbook_data)
+ expect(api_service).to receive(:get).with(cookbook1_url)
+ .and_return(example1_cookbook_data)
+ expect(api_service).to receive(:get).with(cookbook2_url)
+ .and_return(example2_cookbook_data)
- expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example1_cookbook_data).
- and_return(example1_cookbook_object)
- expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example2_cookbook_data).
- and_return(example2_cookbook_object)
+ expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example1_cookbook_data)
+ .and_return(example1_cookbook_object)
+ expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example2_cookbook_data)
+ .and_return(example2_cookbook_object)
end
include_examples "fetching cookbooks when they exist"
@@ -770,15 +847,15 @@ describe Chef::PolicyBuilder::Policyfile do
context "when the cookbooks exist on the server" do
before do
- expect(api_service).to receive(:get).with(cookbook1_url).
- and_return(example1_cookbook_data)
- expect(api_service).to receive(:get).with(cookbook2_url).
- and_return(example2_cookbook_data)
-
- expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example1_cookbook_data).
- and_return(example1_cookbook_object)
- expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example2_cookbook_data).
- and_return(example2_cookbook_object)
+ expect(api_service).to receive(:get).with(cookbook1_url)
+ .and_return(example1_cookbook_data)
+ expect(api_service).to receive(:get).with(cookbook2_url)
+ .and_return(example2_cookbook_data)
+
+ expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example1_cookbook_data)
+ .and_return(example1_cookbook_object)
+ expect(Chef::CookbookVersion).to receive(:from_cb_artifact_data).with(example2_cookbook_data)
+ .and_return(example2_cookbook_object)
end
include_examples "fetching cookbooks when they exist"
diff --git a/spec/unit/property/validation_spec.rb b/spec/unit/property/validation_spec.rb
index 13afcdfbc2..b05d8c4e17 100644
--- a/spec/unit/property/validation_spec.rb
+++ b/spec/unit/property/validation_spec.rb
@@ -617,8 +617,9 @@ describe "Chef::Resource.property validation" do
expect(resource.x 1).to eq 1
expect(resource.x).to eq 1
end
- it "value nil is invalid" do
- expect { resource.x nil }.to raise_error Chef::Exceptions::ValidationFailed
+ it "value nil sets to the default" do
+ # this mildly complicated because the default of a name property is a lazy evaluator to the actual resource.name
+ expect(resource.x nil).to be_a(Chef::DelayedEvaluator)
end
end
@@ -630,8 +631,54 @@ describe "Chef::Resource.property validation" do
expect(resource.x 1).to eq 1
expect(resource.x).to eq 1
end
- it "value nil is invalid" do
- expect { resource.x nil }.to raise_error Chef::Exceptions::ValidationFailed
+ it "value nil sets the default" do
+ expect(resource.x nil).to eq 10
+ expect(resource.x).to eq 10
+ end
+ end
+ end
+
+ context "nil setting default" do
+ with_property ":x, String" do
+ it "if x is not specified, the default is returned" do
+ expect(resource.x).to eq nil
+ end
+ it "value '2' is valid" do
+ expect(resource.x "2").to eq "2"
+ expect(resource.x).to eq "2"
+ end
+ it "value nil sets the default" do
+ resource.x "2"
+ expect(resource.x nil).to eq nil
+ expect(resource.x).to eq nil
+ end
+ end
+ with_property ":x, String, default: '1'" do
+ it "if x is not specified, the default is returned" do
+ expect(resource.x).to eq "1"
+ end
+ it "value '2' is valid" do
+ expect(resource.x "2").to eq "2"
+ expect(resource.x).to eq "2"
+ end
+ it "value nil sets the default" do
+ resource.x "2"
+ expect(resource.x nil).to eq "1"
+ expect(resource.x).to eq "1"
+ end
+ end
+ with_property ":x, [ String, nil ] , default: '1'" do
+ it "if x is not specified, the default is returned" do
+ expect(resource.x).to eq "1"
+ end
+ it "value '2' is valid" do
+ expect(resource.x "2").to eq "2"
+ expect(resource.x).to eq "2"
+ end
+ it "value nil sets to nil" do
+ resource.x "2"
+ expect(resource.x nil).to eq nil
+ expect(resource.x).to eq nil
end
end
end
@@ -699,4 +746,13 @@ describe "Chef::Resource.property validation" do
end
end
end
+
+ context "custom validation messages" do
+ with_property ":x, String, validation_message: 'Must be a string, fool'" do
+ it "raise with the correct error message" do
+ expect { resource.x 1 }.to raise_error Chef::Exceptions::ValidationFailed,
+ "Must be a string, fool"
+ end
+ end
+ end
end
diff --git a/spec/unit/property_spec.rb b/spec/unit/property_spec.rb
index b8cf7f5d1b..793bb3248f 100644
--- a/spec/unit/property_spec.rb
+++ b/spec/unit/property_spec.rb
@@ -64,7 +64,7 @@ describe "Chef::Resource.property" do
if properties.size == 1
description = "With property #{properties.first}"
else
- description = "With properties #{english_join(properties.map { |property| "#{property.inspect}" })}"
+ description = "With properties #{english_join(properties.map { |property| (property.inspect).to_s })}"
end
context description, *tags do
before do
@@ -93,7 +93,7 @@ describe "Chef::Resource.property" do
expect(resource.bare_property).to eq 20
end
it "can be set with =" do
- expect(resource.bare_property 10).to eq 10
+ expect(resource.bare_property = 10).to eq 10
expect(resource.bare_property).to eq 10
end
it "can be set to nil with =" do
@@ -118,6 +118,19 @@ describe "Chef::Resource.property" do
end
end
+ context "deprecated properties" do
+ it "does not create a deprecation warning on definition" do
+ expect { resource_class.class_eval { property :x, String, deprecated: 10 } }.not_to raise_error Chef::Exceptions::DeprecatedFeatureError
+ end
+
+ with_property ":x, deprecated: 'a deprecated property'" do
+ it "deprecated properties emit a deprecation warning" do
+ expect(Chef).to receive(:deprecated).with(:property, "a deprecated property")
+ expect(resource.x 10).to eq 10
+ end
+ end
+ end
+
with_property ":x, name_property: true" do
context "and subclass" do
let(:subresource_class) do
@@ -1037,34 +1050,34 @@ describe "Chef::Resource.property" do
context "default ordering deprecation warnings" do
it "emits an error for property :x, default: 10, #{name}: true" do
- expect { resource_class.property :x, :default => 10, name.to_sym => true }.to raise_error Chef::Exceptions::ArgumentError,
- /Cannot specify both default and name_property\/name_attribute together on property x of resource chef_resource_property_spec_(\d+)/
+ expect { resource_class.property :x, :default => 10, name.to_sym => true }.to raise_error ArgumentError,
+ /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
end
it "emits an error for property :x, default: nil, #{name}: true" do
- expect { resource_class.property :x, :default => nil, name.to_sym => true }.to raise_error Chef::Exceptions::ArgumentError,
- /Cannot specify both default and name_property\/name_attribute together on property x of resource chef_resource_property_spec_(\d+)/
+ expect { resource_class.property :x, :default => nil, name.to_sym => true }.to raise_error ArgumentError,
+ /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
end
it "emits an error for property :x, #{name}: true, default: 10" do
- expect { resource_class.property :x, name.to_sym => true, :default => 10 }.to raise_error Chef::Exceptions::ArgumentError,
- /Cannot specify both default and name_property\/name_attribute together on property x of resource chef_resource_property_spec_(\d+)/
+ expect { resource_class.property :x, name.to_sym => true, :default => 10 }.to raise_error ArgumentError,
+ /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
end
it "emits an error for property :x, #{name}: true, default: nil" do
- expect { resource_class.property :x, name.to_sym => true, :default => nil }.to raise_error Chef::Exceptions::ArgumentError,
- /Cannot specify both default and name_property\/name_attribute together on property x of resource chef_resource_property_spec_(\d+)/
+ expect { resource_class.property :x, name.to_sym => true, :default => nil }.to raise_error ArgumentError,
+ /A property cannot be both a name_property\/name_attribute and have a default value. Use one or the other on property x of resource chef_resource_property_spec_(\d+)/
end
end
end
end
it "raises an error if both name_property and name_attribute are specified" do
- expect { resource_class.property :x, :name_property => false, :name_attribute => 1 }.to raise_error ArgumentError,
- /Cannot specify both name_property and name_attribute together on property x of resource chef_resource_property_spec_(\d+)./
- expect { resource_class.property :x, :name_property => false, :name_attribute => nil }.to raise_error ArgumentError,
- /Cannot specify both name_property and name_attribute together on property x of resource chef_resource_property_spec_(\d+)./
- expect { resource_class.property :x, :name_property => false, :name_attribute => false }.to raise_error ArgumentError,
- /Cannot specify both name_property and name_attribute together on property x of resource chef_resource_property_spec_(\d+)./
- expect { resource_class.property :x, :name_property => true, :name_attribute => true }.to raise_error ArgumentError,
- /Cannot specify both name_property and name_attribute together on property x of resource chef_resource_property_spec_(\d+)./
+ expect { resource_class.property :x, name_property: false, name_attribute: 1 }.to raise_error ArgumentError,
+ /name_attribute and name_property are functionally identical and both cannot be specified on a property at once. Use just one on property x of resource chef_resource_property_spec_(\d+)./
+ expect { resource_class.property :x, name_property: false, name_attribute: nil }.to raise_error ArgumentError,
+ /name_attribute and name_property are functionally identical and both cannot be specified on a property at once. Use just one on property x of resource chef_resource_property_spec_(\d+)./
+ expect { resource_class.property :x, name_property: false, name_attribute: false }.to raise_error ArgumentError,
+ /name_attribute and name_property are functionally identical and both cannot be specified on a property at once. Use just one on property x of resource chef_resource_property_spec_(\d+)./
+ expect { resource_class.property :x, name_property: true, name_attribute: true }.to raise_error ArgumentError,
+ /name_attribute and name_property are functionally identical and both cannot be specified on a property at once. Use just one on property x of resource chef_resource_property_spec_(\d+)./
end
context "property_type" do
@@ -1143,6 +1156,17 @@ describe "Chef::Resource.property" do
end
+ context "with aliased properties" do
+ with_property ":real, Integer" do
+ it "should set the real property and emit a deprecation message" do
+ expect(Chef).to receive(:deprecated).with(:property, "we don't like the deprecated property no more")
+ resource_class.class_eval { deprecated_property_alias :deprecated, :real, "we don't like the deprecated property no more" }
+ resource.deprecated 10
+ expect(resource.real).to eq 10
+ end
+ end
+ end
+
context "redefining Object methods" do
it "disallows redefining Object methods" do
expect { resource_class.class_eval { property :hash } }.to raise_error(ArgumentError)
diff --git a/spec/unit/provider/apt_repository_spec.rb b/spec/unit/provider/apt_repository_spec.rb
index 6180582d69..1601e9f629 100644
--- a/spec/unit/provider/apt_repository_spec.rb
+++ b/spec/unit/provider/apt_repository_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Thom May (<thom@chef.io>)
-# Copyright:: Copyright (c) 2016 Chef Software, Inc.
+# Copyright:: 2016-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,31 +23,30 @@ require "spec_helper"
#
# Output of the command:
# => apt-key adv --list-public-keys --with-fingerprint --with-colons
-APT_KEY_FINGER = <<-EOF
-tru:t:1:1488924856:0:3:1:5
-pub:-:1024:17:40976EAF437D05B5:2004-09-12:::-:Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com>::scESC:
-fpr:::::::::630239CC130E1A7FD81A27B140976EAF437D05B5:
-sub:-:2048:16:251BEFF479164387:2004-09-12::::::e:
-pub:-:1024:17:46181433FBB75451:2004-12-30:::-:Ubuntu CD Image Automatic Signing Key <cdimage@ubuntu.com>::scSC:
-fpr:::::::::C5986B4F1257FFA86632CBA746181433FBB75451:
-pub:-:4096:1:3B4FE6ACC0B21F32:2012-05-11:::-:Ubuntu Archive Automatic Signing Key (2012) <ftpmaster@ubuntu.com>::scSC:
-fpr:::::::::790BC7277767219C42C86F933B4FE6ACC0B21F32:
-pub:-:4096:1:D94AA3F0EFE21092:2012-05-11:::-:Ubuntu CD Image Automatic Signing Key (2012) <cdimage@ubuntu.com>::scSC:
-fpr:::::::::843938DF228D22F7B3742BC0D94AA3F0EFE21092:
+APT_KEY_FINGER = <<~EOF.freeze
+ tru:t:1:1488924856:0:3:1:5
+ pub:-:1024:17:40976EAF437D05B5:2004-09-12:::-:Ubuntu Archive Automatic Signing Key <ftpmaster@ubuntu.com>::scESC:
+ fpr:::::::::630239CC130E1A7FD81A27B140976EAF437D05B5:
+ sub:-:2048:16:251BEFF479164387:2004-09-12::::::e:
+ pub:-:1024:17:46181433FBB75451:2004-12-30:::-:Ubuntu CD Image Automatic Signing Key <cdimage@ubuntu.com>::scSC:
+ fpr:::::::::C5986B4F1257FFA86632CBA746181433FBB75451:
+ pub:-:4096:1:3B4FE6ACC0B21F32:2012-05-11:::-:Ubuntu Archive Automatic Signing Key (2012) <ftpmaster@ubuntu.com>::scSC:
+ fpr:::::::::790BC7277767219C42C86F933B4FE6ACC0B21F32:
+ pub:-:4096:1:D94AA3F0EFE21092:2012-05-11:::-:Ubuntu CD Image Automatic Signing Key (2012) <cdimage@ubuntu.com>::scSC:
+ fpr:::::::::843938DF228D22F7B3742BC0D94AA3F0EFE21092:
EOF
# Output of the command:
# => gpg --with-fingerprint --with-colons [FILE]
-GPG_FINGER = <<-EOF
-pub:-:1024:17:327574EE02A818DD:2009-04-22:::-:Cloudera Apt Repository:
-fpr:::::::::F36A89E33CC1BD0F71079007327574EE02A818DD:
-sub:-:2048:16:84080586D1CA74A1:2009-04-22::::
+GPG_FINGER = <<~EOF.freeze
+ pub:-:1024:17:327574EE02A818DD:2009-04-22:::-:Cloudera Apt Repository:
+ fpr:::::::::F36A89E33CC1BD0F71079007327574EE02A818DD:
+ sub:-:2048:16:84080586D1CA74A1:2009-04-22::::
EOF
describe Chef::Provider::AptRepository do
let(:new_resource) { Chef::Resource::AptRepository.new("multiverse") }
- let(:shellout_env) { { env: { "LANG" => "en_US", "LANGUAGE" => "en_US" } } }
let(:provider) do
node = Chef::Node.new
events = Chef::EventDispatch::Dispatcher.new
@@ -56,19 +55,26 @@ describe Chef::Provider::AptRepository do
end
let(:apt_key_finger_cmd) do
- "apt-key adv --list-public-keys --with-fingerprint --with-colons"
+ %w{apt-key adv --list-public-keys --with-fingerprint --with-colons}
end
let(:apt_key_finger) do
- r = double("Mixlib::ShellOut", stdout: APT_KEY_FINGER, exitstatus: 0, live_stream: true)
- allow(r).to receive(:run_command)
- r
+ double("shell_out", stdout: APT_KEY_FINGER, exitstatus: 0, error?: false)
end
let(:gpg_finger) do
- r = double("Mixlib::ShellOut", stdout: GPG_FINGER, exitstatus: 0, live_stream: true)
- allow(r).to receive(:run_command)
- r
+ double("shell_out", stdout: GPG_FINGER, exitstatus: 0, error?: false)
+ end
+
+ let(:gpg_shell_out_success) do
+ double("shell_out", stdout: "pub 2048R/7BD9BF62 2011-08-19 nginx signing key <signing-key@nginx.com>",
+ exitstatus: 0, error?: false)
+ end
+
+ let(:gpg_shell_out_failure) do
+ double("shell_out", stderr: "gpg: no valid OpenPGP data found.\n
+ gpg: processing message failed: eof",
+ exitstatus: 1, error?: true)
end
let(:apt_fingerprints) do
@@ -83,62 +89,126 @@ C5986B4F1257FFA86632CBA746181433FBB75451
end
describe "#is_key_id?" do
- it "should detect a key" do
+ it "detects a key" do
expect(provider.is_key_id?("A4FF2279")).to be_truthy
end
- it "should detect a key with a hex signifier" do
+ it "detects a key with a hex signifier" do
expect(provider.is_key_id?("0xA4FF2279")).to be_truthy
end
- it "should reject a key with the wrong length" do
+ it "rejects a key with the wrong length" do
expect(provider.is_key_id?("4FF2279")).to be_falsey
end
- it "should reject a key with non-hex characters" do
+ it "rejects a key with non-hex characters" do
expect(provider.is_key_id?("A4KF2279")).to be_falsey
end
end
describe "#extract_fingerprints_from_cmd" do
- before do
- expect(Mixlib::ShellOut).to receive(:new).and_return(apt_key_finger)
+ it "runs the desired command" do
+ expect(provider).to receive(:shell_out).and_return(apt_key_finger)
+ provider.extract_fingerprints_from_cmd(*apt_key_finger_cmd)
end
- it "should run the desired command" do
- expect(apt_key_finger).to receive(:run_command)
- provider.extract_fingerprints_from_cmd(apt_key_finger_cmd)
+ it "returns a list of key fingerprints" do
+ expect(provider).to receive(:shell_out).and_return(apt_key_finger)
+ expect(provider.extract_fingerprints_from_cmd(*apt_key_finger_cmd)).to eql(apt_fingerprints)
end
+ end
- it "should return a list of key fingerprints" do
- expect(provider.extract_fingerprints_from_cmd(apt_key_finger_cmd)).to eql(apt_fingerprints)
+ describe "#cookbook_name" do
+ it "returns 'test' when the cookbook property is set" do
+ new_resource.cookbook("test")
+ expect(provider.cookbook_name).to eq("test")
end
end
describe "#no_new_keys?" do
before do
- allow(provider).to receive(:extract_fingerprints_from_cmd).with(apt_key_finger_cmd).and_return(apt_fingerprints)
+ allow(provider).to receive(:extract_fingerprints_from_cmd).with(*apt_key_finger_cmd).and_return(apt_fingerprints)
end
let(:file) { "/tmp/remote-gpg-keyfile" }
- it "should match a set of keys" do
+ it "matches a set of keys" do
allow(provider).to receive(:extract_fingerprints_from_cmd)
- .with("gpg --with-fingerprint --with-colons #{file}")
+ .with("gpg", "--with-fingerprint", "--with-colons", file)
.and_return(Array(apt_fingerprints.first))
expect(provider.no_new_keys?(file)).to be_truthy
end
- it "should notice missing keys" do
+ it "notices missing keys" do
allow(provider).to receive(:extract_fingerprints_from_cmd)
- .with("gpg --with-fingerprint --with-colons #{file}")
+ .with("gpg", "--with-fingerprint", "--with-colons", file)
.and_return(%w{ F36A89E33CC1BD0F71079007327574EE02A818DD })
expect(provider.no_new_keys?(file)).to be_falsey
end
end
+ describe "#key_type" do
+ it "returns :remote_file with an http URL" do
+ expect(provider.key_type("https://www.chef.io/key")).to eq(:remote_file)
+ end
+
+ it "returns :cookbook_file with a chef managed file" do
+ expect(provider).to receive(:has_cookbook_file?).and_return(true)
+ expect(provider.key_type("/foo/bar.key")).to eq(:cookbook_file)
+ end
+
+ it "throws exception if an unknown file specified" do
+ expect(provider).to receive(:has_cookbook_file?).and_return(false)
+ expect { provider.key_type("/foo/bar.key") }.to raise_error(Chef::Exceptions::FileNotFound)
+ end
+ end
+
+ describe "#keyserver_install_cmd" do
+ it "returns keyserver install command" do
+ expect(provider.keyserver_install_cmd("ABC", "gpg.mit.edu")).to eq("apt-key adv --recv --keyserver hkp://gpg.mit.edu:80 ABC")
+ end
+
+ it "uses proxy if key_proxy property is set" do
+ new_resource.key_proxy("proxy.mycorp.dmz:3128")
+ expect(provider.keyserver_install_cmd("ABC", "gpg.mit.edu")).to eq("apt-key adv --recv --keyserver-options http-proxy=proxy.mycorp.dmz:3128 --keyserver hkp://gpg.mit.edu:80 ABC")
+ end
+
+ it "properly handles keyservers passed with hkp:// URIs" do
+ expect(provider.keyserver_install_cmd("ABC", "hkp://gpg.mit.edu")).to eq("apt-key adv --recv --keyserver hkp://gpg.mit.edu ABC")
+ end
+ end
+
+ describe "#is_ppa_url" do
+ it "returns true if the URL starts with ppa:" do
+ expect(provider.is_ppa_url?("ppa://example.com")).to be_truthy
+ end
+
+ it "returns false if the URL does not start with ppa:" do
+ expect(provider.is_ppa_url?("example.com")).to be_falsey
+ end
+ end
+
+ describe "#repo_components" do
+ it "returns 'main' if a PPA and components property not set" do
+ expect(provider).to receive(:is_ppa_url?).and_return(true)
+ expect(provider.repo_components).to eq("main")
+ end
+
+ it "returns components property if a PPA and components is set" do
+ new_resource.components(["foo"])
+ expect(provider).to receive(:is_ppa_url?).and_return(true)
+ expect(provider.repo_components).to eq(["foo"])
+ end
+
+ it "returns components property if not a PPA" do
+ new_resource.components(["foo"])
+ expect(provider).to receive(:is_ppa_url?).and_return(false)
+ expect(provider.repo_components).to eq(["foo"])
+ end
+ end
+
describe "#install_ppa_key" do
let(:url) { "https://launchpad.net/api/1.0/~chef/+archive/main" }
let(:key) { "C5986B4F1257FFA86632CBA746181433FBB75451" }
- it "should get a key" do
+ it "gets a key" do
simples = double("HTTP")
allow(simples).to receive(:get).and_return("\"#{key}\"")
expect(Chef::HTTP::Simple).to receive(:new).with(url).and_return(simples)
@@ -148,42 +218,37 @@ C5986B4F1257FFA86632CBA746181433FBB75451
end
describe "#make_ppa_url" do
- it "should ignore non-ppa repositories" do
- expect(provider.make_ppa_url("some_string")).to be_nil
- end
-
- it "should create a URL" do
+ it "creates a URL" do
expect(provider).to receive(:install_ppa_key).with("chef", "main").and_return(true)
expect(provider.make_ppa_url("ppa:chef/main")).to eql("http://ppa.launchpad.net/chef/main/ubuntu")
end
end
describe "#build_repo" do
- it "should create a repository string" do
+ it "creates a repository string" do
target = %Q{deb "http://test/uri" unstable main\n}
expect(provider.build_repo("http://test/uri", "unstable", "main", false, nil)).to eql(target)
end
- it "should create a repository string with no distribution" do
+ it "creates a repository string with no distribution" do
target = %Q{deb "http://test/uri" main\n}
expect(provider.build_repo("http://test/uri", nil, "main", false, nil)).to eql(target)
end
- it "should create a repository string with source" do
+ it "creates a repository string with source" do
target = %Q{deb "http://test/uri" unstable main\ndeb-src "http://test/uri" unstable main\n}
expect(provider.build_repo("http://test/uri", "unstable", "main", false, nil, true)).to eql(target)
end
- it "should create a repository string with options" do
+ it "creates a repository string with options" do
target = %Q{deb [trusted=yes] "http://test/uri" unstable main\n}
expect(provider.build_repo("http://test/uri", "unstable", "main", true, nil)).to eql(target)
end
- it "should handle a ppa repo" do
+ it "handles a ppa repo" do
target = %Q{deb "http://ppa.launchpad.net/chef/main/ubuntu" unstable main\n}
expect(provider).to receive(:make_ppa_url).with("ppa:chef/main").and_return("http://ppa.launchpad.net/chef/main/ubuntu")
expect(provider.build_repo("ppa:chef/main", "unstable", "main", false, nil)).to eql(target)
end
end
-
end
diff --git a/spec/unit/provider/apt_update_spec.rb b/spec/unit/provider/apt_update_spec.rb
index e1ab0085ce..5cd327b66b 100644
--- a/spec/unit/provider/apt_update_spec.rb
+++ b/spec/unit/provider/apt_update_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Thom May (<thom@chef.io>)
-# Copyright:: Copyright (c) 2016-2017, Chef Software Inc.
+# Copyright:: Copyright (c) 2016-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -37,6 +37,8 @@ describe Chef::Provider::AptUpdate do
Chef::Provider::AptUpdate.new(new_resource, run_context)
end
+ let(:apt_update_cmd) { %w{apt-get -q update} }
+
it "responds to load_current_resource" do
expect(provider).to respond_to(:load_current_resource)
end
@@ -45,7 +47,7 @@ describe Chef::Provider::AptUpdate do
before do
FileUtils.rmdir config_dir
expect(File.exist?(config_dir)).to be false
- allow_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ allow_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
end
it "should create the directory" do
@@ -64,7 +66,7 @@ describe Chef::Provider::AptUpdate do
describe "#action_update" do
it "should update the apt cache" do
provider.load_current_resource
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
provider.run_action(:update)
expect(new_resource).to be_updated_by_last_action
end
@@ -79,14 +81,14 @@ describe Chef::Provider::AptUpdate do
it "should run if the time stamp is old" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 86_500)
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
provider.run_action(:periodic)
expect(new_resource).to be_updated_by_last_action
end
it "should not run if the time stamp is new" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now)
- expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
provider.run_action(:periodic)
expect(new_resource).to_not be_updated_by_last_action
end
@@ -98,14 +100,14 @@ describe Chef::Provider::AptUpdate do
it "should run if the time stamp is old" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 500)
- expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ expect_any_instance_of(Chef::Provider::Execute).to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
provider.run_action(:periodic)
expect(new_resource).to be_updated_by_last_action
end
it "should not run if the time stamp is new" do
expect(File).to receive(:mtime).with("#{stamp_dir}/update-success-stamp").and_return(Time.now - 300)
- expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_with_systems_locale!).with("apt-get -q update", anything())
+ expect_any_instance_of(Chef::Provider::Execute).not_to receive(:shell_out_compacted!).with(*apt_update_cmd, anything())
provider.run_action(:periodic)
expect(new_resource).to_not be_updated_by_last_action
end
diff --git a/spec/unit/provider/cookbook_file/content_spec.rb b/spec/unit/provider/cookbook_file/content_spec.rb
index 096ac85b64..4e07915a95 100644
--- a/spec/unit/provider/cookbook_file/content_spec.rb
+++ b/spec/unit/provider/cookbook_file/content_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Provider::CookbookFile::Content do
- let(:new_resource) { double("Chef::Resource::CookbookFile (new)", :cookbook_name => "apache2", :cookbook => "apache2") }
+ let(:new_resource) { double("Chef::Resource::CookbookFile (new)", cookbook_name: "apache2", cookbook: "apache2") }
let(:content) do
@run_context = double("Chef::RunContext")
@current_resource = double("Chef::Resource::CookbookFile (current)")
diff --git a/spec/unit/provider/cookbook_file_spec.rb b/spec/unit/provider/cookbook_file_spec.rb
index f49cc7d3da..e1ef3c63d8 100644
--- a/spec/unit/provider/cookbook_file_spec.rb
+++ b/spec/unit/provider/cookbook_file_spec.rb
@@ -25,7 +25,8 @@ 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(:run_context) { double("Chef::RunContext", :node => node, :events => events) }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
let(:enclosing_directory) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
diff --git a/spec/unit/provider/cron/unix_spec.rb b/spec/unit/provider/cron/unix_spec.rb
index 5e1fcb35ab..c8ef82e37a 100644
--- a/spec/unit/provider/cron/unix_spec.rb
+++ b/spec/unit/provider/cron/unix_spec.rb
@@ -37,36 +37,41 @@ describe Chef::Provider::Cron::Unix do
end
end
- let(:status) { double("Process::Status", :exitstatus => exitstatus) }
+ let(:status) { double("Process::Status", exitstatus: exitstatus) }
let(:exitstatus) { 0 }
- let(:shell_out) { double("Mixlib::ShellOut", :status => status, :stdout => stdout, :stderr => stderr) }
+ let(:shell_out) { double("Mixlib::ShellOut", status: status, stdout: stdout, stderr: stderr) }
+
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
it "is a Chef::Provider:Cron" do
expect(provider).to be_a(Chef::Provider::Cron)
end
+ before do
+ allow(run_context).to receive(:logger).and_return(logger)
+ end
describe "read_crontab" do
let(:stderr) { "" }
let(:stdout) do
- String.new(<<-CRONTAB)
-0 2 * * * /some/other/command
+ String.new(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-* 5 * * * /bin/true
+ # Chef Name: something else
+ * 5 * * * /bin/true
-# Another comment
+ # Another comment
CRONTAB
end
before do
- allow(Chef::Log).to receive(:debug)
+ allow(logger).to receive(:trace)
allow(shell_out).to receive(:format_for_exception).and_return("formatted command output")
- allow(provider).to receive(:shell_out).with("/usr/bin/crontab -l", :user => username).and_return(shell_out)
+ allow(provider).to receive(:shell_out_compacted).with("/usr/bin/crontab", "-l", user: username).and_return(shell_out)
end
it "should call crontab -l with the user" do
provider.send(:read_crontab)
- expect(provider).to have_received(:shell_out).with("/usr/bin/crontab -l", :user => username)
+ expect(provider).to have_received(:shell_out_compacted).with("/usr/bin/crontab", "-l", user: username)
end
it "should return the contents of the crontab" do
@@ -83,7 +88,7 @@ describe Chef::Provider::Cron::Unix do
it "logs the crontab output to debug" do
provider.send(:read_crontab)
- expect(Chef::Log).to have_received(:debug).with("formatted command output")
+ expect(logger).to have_received(:trace).with("formatted command output")
end
end
@@ -98,7 +103,7 @@ describe Chef::Provider::Cron::Unix do
it "logs the crontab output to debug" do
provider.send(:read_crontab) rescue nil
- expect(Chef::Log).to have_received(:debug).with("formatted command output")
+ expect(logger).to have_received(:trace).with("formatted command output")
end
end
end
@@ -106,7 +111,7 @@ describe Chef::Provider::Cron::Unix do
describe "write_crontab" do
let(:stdout) { "" }
let(:stderr) { "" }
- let(:tempfile) { double("foo", :path => "/tmp/foo", :close => true) }
+ let(:tempfile) { double("foo", path: "/tmp/foo", close: true) }
before do
expect(Tempfile).to receive(:new).and_return(tempfile)
@@ -114,12 +119,12 @@ describe Chef::Provider::Cron::Unix do
expect(tempfile).to receive(:chmod).with(420)
expect(tempfile).to receive(:close!)
allow(tempfile).to receive(:<<)
- allow(provider).to receive(:shell_out).with("/usr/bin/crontab #{tempfile.path}", :user => username).and_return(shell_out)
+ allow(provider).to receive(:shell_out_compacted).with("/usr/bin/crontab", tempfile.path, user: username).and_return(shell_out)
end
it "should call crontab for the user" do
provider.send(:write_crontab, "Foo")
- expect(provider).to have_received(:shell_out).with("/usr/bin/crontab #{tempfile.path}", :user => username)
+ expect(provider).to have_received(:shell_out_compacted).with("/usr/bin/crontab", tempfile.path, user: username)
end
it "should call crontab with a file containing the crontab" do
diff --git a/spec/unit/provider/cron_spec.rb b/spec/unit/provider/cron_spec.rb
index ef629ebd52..67d578e2ea 100644
--- a/spec/unit/provider/cron_spec.rb
+++ b/spec/unit/provider/cron_spec.rb
@@ -19,31 +19,38 @@
require "spec_helper"
describe Chef::Provider::Cron do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
+ before do
+ @node = Chef::Node.new
+ @events = Chef::EventDispatch::Dispatcher.new
+ @run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
+
+ @new_resource = Chef::Resource::Cron.new("cronhole some stuff", @run_context)
+ @new_resource.user "root"
+ @new_resource.minute "30"
+ @new_resource.command "/bin/true"
+ @provider = Chef::Provider::Cron.new(@new_resource, @run_context)
+ end
+
describe "when with special time string" do
before do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
-
- @new_resource = Chef::Resource::Cron.new("cronhole some stuff", @run_context)
- @new_resource.user "root"
- @new_resource.minute "30"
- @new_resource.command "/bin/true"
@new_resource.time :reboot
@provider = Chef::Provider::Cron.new(@new_resource, @run_context)
end
context "with a matching entry in the user's crontab" do
before :each do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-@reboot /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ @reboot /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
@@ -60,19 +67,19 @@ CRONTAB
end
it "should pull env vars out" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
-
-# Chef Name: cronhole some stuff
-MAILTO=foo@example.com
-SHELL=/bin/foosh
-PATH=/bin:/foo
-HOME=/home/foo
-@reboot /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
-
-# Another comment
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
+
+ # Chef Name: cronhole some stuff
+ MAILTO=foo@example.com
+ SHELL=/bin/foosh
+ PATH=/bin:/foo
+ HOME=/home/foo
+ @reboot /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
+
+ # Another comment
CRONTAB
cron = @provider.load_current_resource
expect(cron.mailto).to eq("foo@example.com")
@@ -84,12 +91,12 @@ CRONTAB
end
it "should parse and load generic and standard environment variables from cron entry" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-# Chef Name: cronhole some stuff
-MAILTO=warn@example.com
-TEST=lol
-FLAG=1
-@reboot /bin/true
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ # Chef Name: cronhole some stuff
+ MAILTO=warn@example.com
+ TEST=lol
+ FLAG=1
+ @reboot /bin/true
CRONTAB
cron = @provider.load_current_resource
@@ -98,13 +105,13 @@ CRONTAB
end
it "should not break with variables that match the cron resource internals" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-# Chef Name: cronhole some stuff
-MINUTE=40
-REBOOT=midnight
-TEST=lol
-ENVIRONMENT=production
-@reboot /bin/true
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ # Chef Name: cronhole some stuff
+ MINUTE=40
+ REBOOT=midnight
+ TEST=lol
+ ENVIRONMENT=production
+ @reboot /bin/true
CRONTAB
cron = @provider.load_current_resource
@@ -113,7 +120,7 @@ CRONTAB
end
it "should report the match" do
- expect(Chef::Log).to receive(:debug).with("Found cron '#{@new_resource.name}'")
+ expect(logger).to receive(:trace).with("Found cron '#{@new_resource.name}'")
@provider.load_current_resource
end
@@ -130,9 +137,9 @@ CRONTAB
end
it "should create a crontab with the entry" do
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-# Chef Name: cronhole some stuff
-@reboot /bin/true
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ # Chef Name: cronhole some stuff
+ @reboot /bin/true
ENDCRON
@provider.run_action(:create)
end
@@ -141,18 +148,6 @@ CRONTAB
end
end
- before do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
-
- @new_resource = Chef::Resource::Cron.new("cronhole some stuff", @run_context)
- @new_resource.user "root"
- @new_resource.minute "30"
- @new_resource.command "/bin/true"
- @provider = Chef::Provider::Cron.new(@new_resource, @run_context)
- end
-
describe "when examining the current system state" do
context "with no crontab for the user" do
before :each do
@@ -166,20 +161,20 @@ CRONTAB
end
it "should report an empty crontab" do
- expect(Chef::Log).to receive(:debug).with("Cron empty for '#{@new_resource.user}'")
+ expect(logger).to receive(:trace).with("Cron empty for '#{@new_resource.user}'")
@provider.load_current_resource
end
end
context "with no matching entry in the user's crontab" do
before :each do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-* 5 * * * /bin/true
+ # Chef Name: something else
+ * 5 * * * /bin/true
-# Another comment
+ # Another comment
CRONTAB
end
@@ -190,14 +185,14 @@ CRONTAB
end
it "should report no entry found" do
- expect(Chef::Log).to receive(:debug).with("Cron '#{@new_resource.name}' not found")
+ expect(logger).to receive(:trace).with("Cron '#{@new_resource.name}' not found")
@provider.load_current_resource
end
it "should not fail if there's an existing cron with a numerical argument" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-# Chef Name: foo[bar] (baz)
-21 */4 * * * some_prog 1234567
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ # Chef Name: foo[bar] (baz)
+ 21 */4 * * * some_prog 1234567
CRONTAB
expect do
@provider.load_current_resource
@@ -207,15 +202,15 @@ CRONTAB
context "with a matching entry in the user's crontab" do
before :each do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-* 5 * 1 * /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ * 5 * 1 * /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
@@ -237,19 +232,19 @@ CRONTAB
end
it "should pull env vars out" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
-
-# Chef Name: cronhole some stuff
-MAILTO=foo@example.com
-SHELL=/bin/foosh
-PATH=/bin:/foo
-HOME=/home/foo
-* 5 * 1 * /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
-
-# Another comment
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
+
+ # Chef Name: cronhole some stuff
+ MAILTO=foo@example.com
+ SHELL=/bin/foosh
+ PATH=/bin:/foo
+ HOME=/home/foo
+ * 5 * 1 * /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
+
+ # Another comment
CRONTAB
cron = @provider.load_current_resource
expect(cron.mailto).to eq("foo@example.com")
@@ -266,12 +261,12 @@ CRONTAB
end
it "should parse and load generic and standard environment variables from cron entry" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-# Chef Name: cronhole some stuff
-MAILTO=warn@example.com
-TEST=lol
-FLAG=1
-* 5 * * * /bin/true
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ # Chef Name: cronhole some stuff
+ MAILTO=warn@example.com
+ TEST=lol
+ FLAG=1
+ * 5 * * * /bin/true
CRONTAB
cron = @provider.load_current_resource
@@ -280,13 +275,13 @@ CRONTAB
end
it "should not break with variabels that match the cron resource internals" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-# Chef Name: cronhole some stuff
-MINUTE=40
-HOUR=midnight
-TEST=lol
-ENVIRONMENT=production
-* 5 * * * /bin/true
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ # Chef Name: cronhole some stuff
+ MINUTE=40
+ HOUR=midnight
+ TEST=lol
+ ENVIRONMENT=production
+ * 5 * * * /bin/true
CRONTAB
cron = @provider.load_current_resource
@@ -296,22 +291,22 @@ CRONTAB
end
it "should report the match" do
- expect(Chef::Log).to receive(:debug).with("Found cron '#{@new_resource.name}'")
+ expect(logger).to receive(:trace).with("Found cron '#{@new_resource.name}'")
@provider.load_current_resource
end
end
context "with a matching entry in the user's crontab using month names and weekday names (#CHEF-3178)" do
before :each do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-* 5 * Jan Mon /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ * 5 * Jan Mon /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
@@ -332,17 +327,17 @@ CRONTAB
end
it "should report the match" do
- expect(Chef::Log).to receive(:debug).with("Found cron '#{@new_resource.name}'")
+ expect(logger).to receive(:trace).with("Found cron '#{@new_resource.name}'")
@provider.load_current_resource
end
end
context "with a matching entry without a crontab line" do
it "should set cron_exists and leave current_resource values at defaults" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
+ # Chef Name: cronhole some stuff
CRONTAB
cron = @provider.load_current_resource
expect(@provider.cron_exists).to eq(true)
@@ -356,11 +351,11 @@ CRONTAB
end
it "should not pick up a commented out crontab line" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-#* 5 * 1 * /bin/true param1 param2
+ # Chef Name: cronhole some stuff
+ #* 5 * 1 * /bin/true param1 param2
CRONTAB
cron = @provider.load_current_resource
expect(@provider.cron_exists).to eq(true)
@@ -374,15 +369,15 @@ CRONTAB
end
it "should not pick up a later crontab entry" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-#* 5 * 1 * /bin/true param1 param2
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ #* 5 * 1 * /bin/true param1 param2
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
cron = @provider.load_current_resource
expect(@provider.cron_exists).to eq(true)
@@ -447,9 +442,9 @@ CRONTAB
end
it "should create a crontab with the entry" do
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-# Chef Name: cronhole some stuff
-30 * * * * /bin/true
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ # Chef Name: cronhole some stuff
+ 30 * * * * /bin/true
ENDCRON
@provider.run_action(:create)
end
@@ -460,14 +455,14 @@ CRONTAB
@new_resource.shell "/bin/foosh"
@new_resource.home "/home/foo"
@new_resource.environment "TEST" => "LOL"
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-# Chef Name: cronhole some stuff
-MAILTO="foo@example.com"
-PATH="/usr/bin:/my/custom/path"
-SHELL="/bin/foosh"
-HOME="/home/foo"
-TEST=LOL
-30 * * * * /bin/true
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ # Chef Name: cronhole some stuff
+ MAILTO="foo@example.com"
+ PATH="/usr/bin:/my/custom/path"
+ SHELL="/bin/foosh"
+ HOME="/home/foo"
+ TEST=LOL
+ 30 * * * * /bin/true
ENDCRON
@provider.run_action(:create)
end
@@ -478,7 +473,7 @@ TEST=LOL
end
it "should log the action" do
- expect(Chef::Log).to receive(:info).with("cron[cronhole some stuff] added crontab entry")
+ expect(logger).to receive(:info).with("cron[cronhole some stuff] added crontab entry")
@provider.run_action(:create)
end
end
@@ -486,26 +481,26 @@ TEST=LOL
context "when there is a crontab with no matching section" do
before :each do
@provider.cron_exists = false
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
it "should add the entry to the crontab" do
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
-# Chef Name: cronhole some stuff
-30 * * * * /bin/true
+ # Another comment
+ # Chef Name: cronhole some stuff
+ 30 * * * * /bin/true
ENDCRON
@provider.run_action(:create)
end
@@ -516,20 +511,20 @@ TEST=LOL
@new_resource.shell "/bin/foosh"
@new_resource.home "/home/foo"
@new_resource.environment "TEST" => "LOL"
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
-
-# Chef Name: something else
-2 * 1 * * /bin/false
-
-# Another comment
-# Chef Name: cronhole some stuff
-MAILTO="foo@example.com"
-PATH="/usr/bin:/my/custom/path"
-SHELL="/bin/foosh"
-HOME="/home/foo"
-TEST=LOL
-30 * * * * /bin/true
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
+
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
+
+ # Another comment
+ # Chef Name: cronhole some stuff
+ MAILTO="foo@example.com"
+ PATH="/usr/bin:/my/custom/path"
+ SHELL="/bin/foosh"
+ HOME="/home/foo"
+ TEST=LOL
+ 30 * * * * /bin/true
ENDCRON
@provider.run_action(:create)
end
@@ -540,7 +535,7 @@ TEST=LOL
end
it "should log the action" do
- expect(Chef::Log).to receive(:info).with("cron[cronhole some stuff] added crontab entry")
+ expect(logger).to receive(:info).with("cron[cronhole some stuff] added crontab entry")
@provider.run_action(:create)
end
end
@@ -549,28 +544,28 @@ TEST=LOL
before :each do
@provider.cron_exists = true
allow(@provider).to receive(:cron_different?).and_return(true)
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ 30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
it "should update the crontab entry" do
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-30 * * * * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ 30 * * * * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:create)
end
@@ -581,20 +576,20 @@ TEST=LOL
@new_resource.shell "/bin/foosh"
@new_resource.home "/home/foo"
@new_resource.environment "TEST" => "LOL"
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
-
-# Chef Name: cronhole some stuff
-MAILTO="foo@example.com"
-PATH="/usr/bin:/my/custom/path"
-SHELL="/bin/foosh"
-HOME="/home/foo"
-TEST=LOL
-30 * * * * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
-
-# Another comment
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
+
+ # Chef Name: cronhole some stuff
+ MAILTO="foo@example.com"
+ PATH="/usr/bin:/my/custom/path"
+ SHELL="/bin/foosh"
+ HOME="/home/foo"
+ TEST=LOL
+ 30 * * * * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
+
+ # Another comment
ENDCRON
@provider.run_action(:create)
end
@@ -605,7 +600,7 @@ TEST=LOL
end
it "should log the action" do
- expect(Chef::Log).to receive(:info).with("cron[cronhole some stuff] updated crontab entry")
+ expect(logger).to receive(:info).with("cron[cronhole some stuff] updated crontab entry")
@provider.run_action(:create)
end
end
@@ -617,78 +612,78 @@ TEST=LOL
end
it "should add the crontab to the entry" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
+ # Chef Name: cronhole some stuff
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-30 * * * * /bin/true
+ # Chef Name: cronhole some stuff
+ 30 * * * * /bin/true
ENDCRON
@provider.run_action(:create)
end
it "should not blat any following entries" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-#30 * * * * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ #30 * * * * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-30 * * * * /bin/true
-#30 * * * * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ 30 * * * * /bin/true
+ #30 * * * * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:create)
end
it "should handle env vars with no crontab" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-MAILTO=bar@example.com
-PATH=/usr/bin:/my/custom/path
-SHELL=/bin/barsh
-HOME=/home/foo
+ # Chef Name: cronhole some stuff
+ MAILTO=bar@example.com
+ PATH=/usr/bin:/my/custom/path
+ SHELL=/bin/barsh
+ HOME=/home/foo
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
@new_resource.mailto "foo@example.com"
@new_resource.path "/usr/bin:/my/custom/path"
@new_resource.shell "/bin/foosh"
@new_resource.home "/home/foo"
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-MAILTO="foo@example.com"
-PATH="/usr/bin:/my/custom/path"
-SHELL="/bin/foosh"
-HOME="/home/foo"
-30 * * * * /bin/true
+ # Chef Name: cronhole some stuff
+ MAILTO="foo@example.com"
+ PATH="/usr/bin:/my/custom/path"
+ SHELL="/bin/foosh"
+ HOME="/home/foo"
+ 30 * * * * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:create)
end
@@ -698,13 +693,13 @@ HOME="/home/foo"
before :each do
@provider.cron_exists = true
allow(@provider).to receive(:cron_different?).and_return(false)
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-* 5 * * * /bin/true
+ # Chef Name: cronhole some stuff
+ * 5 * * * /bin/true
-# Another comment
+ # Another comment
CRONTAB
end
@@ -719,8 +714,8 @@ CRONTAB
end
it "should log nothing changed" do
- expect(Chef::Log).to receive(:debug).with("Found cron '#{@new_resource.name}'")
- expect(Chef::Log).to receive(:debug).with("Skipping existing cron entry '#{@new_resource.name}'")
+ expect(logger).to receive(:trace).with("Found cron '#{@new_resource.name}'")
+ expect(logger).to receive(:trace).with("Skipping existing cron entry '#{@new_resource.name}'")
@provider.run_action(:create)
end
end
@@ -739,7 +734,7 @@ CRONTAB
it "should do nothing" do
expect(@provider).not_to receive(:write_crontab)
- expect(Chef::Log).not_to receive(:info)
+ expect(logger).not_to receive(:info)
@provider.run_action(:delete)
end
@@ -752,50 +747,50 @@ CRONTAB
context "when the user has a crontab with a matching section" do
before :each do
@provider.cron_exists = true
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ 30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
end
it "should remove the entry" do
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:delete)
end
it "should remove any env vars with the entry" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-MAILTO=foo@example.com
-FOO=test
-30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ MAILTO=foo@example.com
+ FOO=test
+ 30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:delete)
end
@@ -806,7 +801,7 @@ FOO=test
end
it "should log the action" do
- expect(Chef::Log).to receive(:info).with("#{@new_resource} deleted crontab entry")
+ expect(logger).to receive(:info).with("#{@new_resource} deleted crontab entry")
@provider.run_action(:delete)
end
end
@@ -817,61 +812,61 @@ FOO=test
end
it "should remove the section" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
+ # Chef Name: cronhole some stuff
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
ENDCRON
@provider.run_action(:delete)
end
it "should not blat following sections" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-#30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ #30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-#30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ #30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:delete)
end
it "should remove any envvars with the section" do
- allow(@provider).to receive(:read_crontab).and_return(<<-CRONTAB)
-0 2 * * * /some/other/command
+ allow(@provider).to receive(:read_crontab).and_return(<<~CRONTAB)
+ 0 2 * * * /some/other/command
-# Chef Name: cronhole some stuff
-MAILTO=foo@example.com
-#30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ # Chef Name: cronhole some stuff
+ MAILTO=foo@example.com
+ #30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
CRONTAB
- expect(@provider).to receive(:write_crontab).with(<<-ENDCRON)
-0 2 * * * /some/other/command
+ expect(@provider).to receive(:write_crontab).with(<<~ENDCRON)
+ 0 2 * * * /some/other/command
-#30 * * 3 * /bin/true
-# Chef Name: something else
-2 * 1 * * /bin/false
+ #30 * * 3 * /bin/true
+ # Chef Name: something else
+ 2 * 1 * * /bin/false
-# Another comment
+ # Another comment
ENDCRON
@provider.run_action(:delete)
end
@@ -880,13 +875,13 @@ MAILTO=foo@example.com
describe "read_crontab" do
before :each do
- @stdout = <<-CRONTAB
-0 2 * * * /some/other/command
+ @stdout = <<~CRONTAB
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-* 5 * * * /bin/true
+ # Chef Name: something else
+ * 5 * * * /bin/true
-# Another comment
+ # Another comment
CRONTAB
@status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
@@ -899,13 +894,13 @@ MAILTO=foo@example.com
it "should return the contents of the crontab" do
crontab = @provider.send(:read_crontab)
- expect(crontab).to eq <<-CRONTAB
-0 2 * * * /some/other/command
+ expect(crontab).to eq <<~CRONTAB
+ 0 2 * * * /some/other/command
-# Chef Name: something else
-* 5 * * * /bin/true
+ # Chef Name: something else
+ * 5 * * * /bin/true
-# Another comment
+ # Another comment
CRONTAB
end
diff --git a/spec/unit/provider/deploy/revision_spec.rb b/spec/unit/provider/deploy/revision_spec.rb
deleted file mode 100644
index 8f8280e11d..0000000000
--- a/spec/unit/provider/deploy/revision_spec.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Provider::Deploy::Revision do
-
- before do
- allow(ChefConfig).to receive(:windows?) { false }
- @temp_dir = Dir.mktmpdir
- Chef::Config[:file_cache_path] = @temp_dir
- @resource = Chef::Resource::Deploy.new("/my/deploy/dir")
- @resource.revision("8a3195bf3efa246f743c5dfa83683201880f935c")
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @provider = Chef::Provider::Deploy::Revision.new(@resource, @run_context)
- @provider.load_current_resource
- @runner = double("runnah")
- allow(Chef::Runner).to receive(:new).and_return(@runner)
- @expected_release_dir = "/my/deploy/dir/releases/8a3195bf3efa246f743c5dfa83683201880f935c"
- end
-
- after do
- # Make sure we don't keep any state in our tests
- 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")
- end
-
- it "deploys to a dir named after the revision" do
- expect(@provider.release_path).to eq(@expected_release_dir)
- end
-
- it "stores the release dir in the file cache in the cleanup step" do
- allow(FileUtils).to receive(:mkdir_p)
- allow(FileUtils).to receive(:cp_r)
- @provider.cleanup!
- allow(@provider).to receive(:release_slug).and_return("73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2")
- @provider.load_current_resource
- @provider.cleanup!
- second_release = "/my/deploy/dir/releases/73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2"
-
- 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
- allow(FileUtils).to receive(:mkdir_p)
- allow(FileUtils).to receive(:cp_r)
- @provider.cleanup!
- allow(@provider).to receive(:release_slug).and_return("73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2")
- @provider.load_current_resource
- @provider.cleanup!
- second_release = "/my/deploy/dir/releases/73219b87e977d9c7ba1aa57e9ad1d88fa91a0ec2"
- expect(@provider.all_releases).to eq([@expected_release_dir, second_release])
- @provider.cleanup!
-
- allow(@provider).to receive(:release_slug).and_return("8a3195bf3efa246f743c5dfa83683201880f935c")
- @provider.load_current_resource
- @provider.cleanup!
- expect(@provider.all_releases).to eq([second_release, @expected_release_dir])
- end
-
- 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}"
- end
- release_paths.each do |release_path|
- @provider.send(:release_created, release_path)
- end
- expect(@provider.all_releases).to eq(release_paths)
-
- allow(FileUtils).to receive(:rm_rf)
- @provider.cleanup!
-
- expected_release_paths = (%w{second third fourth fifth} << @resource.revision).map do |release_name|
- "/my/deploy/dir/releases/#{release_name}"
- end
-
- expect(@provider.all_releases).to eq(expected_release_paths)
- end
-
- it "regenerates the file cache if it's not available" do
- oldest = "/my/deploy/dir/releases/oldest"
- latest = "/my/deploy/dir/releases/latest"
- expect(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return([latest, oldest])
- expect(::File).to receive(:ctime).with(oldest).and_return(Time.now - 10)
- 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
deleted file mode 100644
index fdb90bf438..0000000000
--- a/spec/unit/provider/deploy/timestamped_spec.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-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)
- @expected_release_dir = "/my/deploy/dir/releases/20040815162342"
- @resource = Chef::Resource::Deploy.new("/my/deploy/dir")
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @timestamped_deploy = Chef::Provider::Deploy::Timestamped.new(@resource, @run_context)
- @runner = double("runnah")
- allow(Chef::Runner).to receive(:new).and_return(@runner)
- end
-
- 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
deleted file mode 100644
index b0ede7e260..0000000000
--- a/spec/unit/provider/deploy_spec.rb
+++ /dev/null
@@ -1,641 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-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)
- allow(Time).to receive(:now).and_return(@release_time)
- @expected_release_dir = "/my/deploy/dir/releases/20040815162342"
- @resource = Chef::Resource::Deploy.new("/my/deploy/dir")
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @provider = Chef::Provider::Deploy.new(@resource, @run_context)
- allow(@provider).to receive(:release_slug)
- allow(@provider).to receive(:release_path).and_return(@expected_release_dir)
- end
-
- it "loads scm resource" do
- expect(@provider.scm_provider).to receive(:load_current_resource)
- @provider.load_current_resource
- end
-
- it "supports :deploy and :rollback actions" do
- expect(@provider).to respond_to(:action_deploy)
- expect(@provider).to respond_to(:action_rollback)
- end
-
- context "when the deploy resource has a timeout attribute" do
- let(:ten_seconds) { 10 }
- before { @resource.timeout(ten_seconds) }
- it "relays the timeout to the scm resource" do
- expect(@provider.scm_provider.new_resource.timeout).to eq(ten_seconds)
- end
- end
-
- context "when the deploy resource has no timeout attribute" do
- it "should not set a timeout on the scm resource" do
- expect(@provider.scm_provider.new_resource.timeout).to be_nil
- end
- end
-
- context "when the deploy_to dir does not exist yet" do
- before do
- expect(FileUtils).to receive(:mkdir_p).with(@resource.deploy_to).ordered
- expect(FileUtils).to receive(:mkdir_p).with(@resource.shared_path).ordered
- allow(::File).to receive(:directory?).and_return(false)
- allow(@provider).to receive(:symlink)
- allow(@provider).to receive(:migrate)
- allow(@provider).to receive(:copy_cached_repo)
- end
-
- it "creates deploy_to dir" do
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).exactly(4).times
- expect(@provider).to receive(:enforce_ownership).twice
- allow(@provider).to receive(:update_cached_repo)
- @provider.deploy
- end
-
- end
-
- it "does not create deploy_to dir if it exists" do
- allow(::File).to receive(:directory?).and_return(true)
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).exactly(4).times
- expect(FileUtils).not_to receive(:mkdir_p).with(@resource.deploy_to)
- expect(FileUtils).not_to receive(:mkdir_p).with(@resource.shared_path)
- expect(@provider).to receive(:enforce_ownership).twice
- allow(@provider).to receive(:copy_cached_repo)
- allow(@provider).to receive(:update_cached_repo)
- allow(@provider).to receive(:symlink)
- allow(@provider).to receive(:migrate)
- @provider.deploy
- end
-
- it "ensures the deploy_to dir ownership after the verfication that it exists" do
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).exactly(4).times
- expect(@provider).to receive(:verify_directories_exist).ordered
- expect(@provider).to receive(:enforce_ownership).ordered
- allow(@provider).to receive(:copy_cached_repo)
- allow(@provider).to receive(:update_cached_repo)
- allow(@provider).to receive(:install_gems)
- expect(@provider).to receive(:enforce_ownership).ordered
- allow(@provider).to receive(:enforce_ownership)
- allow(@provider).to receive(:symlink)
- allow(@provider).to receive(:migrate)
- @provider.deploy
- end
-
- it "updates and copies the repo, then does a migrate, symlink, restart, restart, cleanup on deploy" do
- allow(FileUtils).to receive(:mkdir_p).with("/my/deploy/dir")
- allow(FileUtils).to receive(:mkdir_p).with("/my/deploy/dir/shared")
- expect(@provider).to receive(:enforce_ownership).twice
- expect(@provider).to receive(:update_cached_repo)
- expect(@provider).to receive(:copy_cached_repo)
- expect(@provider).to receive(:install_gems)
- expect(@provider).to receive(:callback).with(:before_migrate, nil)
- expect(@provider).to receive(:migrate)
- expect(@provider).to receive(:callback).with(:before_symlink, nil)
- expect(@provider).to receive(:symlink)
- expect(@provider).to receive(:callback).with(:before_restart, nil)
- expect(@provider).to receive(:restart)
- expect(@provider).to receive(:callback).with(:after_restart, nil)
- expect(@provider).to receive(:cleanup!)
- @provider.deploy
- end
-
- it "should not deploy if there is already a deploy at release_path, and it is the current release" do
- allow(@provider).to receive(:all_releases).and_return([@expected_release_dir])
- allow(@provider).to receive(:current_release?).with(@expected_release_dir).and_return(true)
- expect(@provider).not_to receive(:deploy)
- @provider.run_action(:deploy)
- end
-
- it "should call action_rollback if there is already a deploy of this revision at release_path, and it is not the current release" do
- allow(@provider).to receive(:all_releases).and_return([@expected_release_dir, "102021"])
- allow(@provider).to receive(:current_release?).with(@expected_release_dir).and_return(false)
- expect(@provider).to receive(:rollback_to).with(@expected_release_dir)
- expect(@provider).to receive(:current_release?)
- @provider.run_action(:deploy)
- end
-
- it "calls deploy when deploying a new release" do
- allow(@provider).to receive(:all_releases).and_return([])
- expect(@provider).to receive(:deploy)
- @provider.run_action(:deploy)
- end
-
- it "runs action svn_force_export when new_resource.svn_force_export is true" do
- @resource.svn_force_export true
- expect(@provider.scm_provider).to receive(:run_action).with(:force_export)
- @provider.update_cached_repo
- end
-
- it "Removes the old release before deploying when force deploying over it" do
- allow(@provider).to receive(:all_releases).and_return([@expected_release_dir])
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir)
- expect(@provider).to receive(:deploy)
- @provider.run_action(:force_deploy)
- end
-
- it "deploys as normal when force deploying and there's no prior release at the same path" do
- allow(@provider).to receive(:all_releases).and_return([])
- expect(@provider).to receive(:deploy)
- @provider.run_action(:force_deploy)
- end
-
- 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(:previous_release_path).and_return("previous_release")
- expect(@provider).not_to receive(:rollback)
- expect do
- @provider.run_action(:deploy)
- end.to raise_exception(RuntimeError, "Unexpected error")
- end
-
- 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(:previous_release_path).and_return("previous_release")
- expect(@provider).to receive(:rollback)
- expect do
- @provider.run_action(:deploy)
- end.to raise_exception(RuntimeError, "Unexpected error")
- end
-
- describe "on systems without broken Dir.glob results" do
- it "sets the release path to the penultimate release when one is not specified, symlinks, and rm's the last release on rollback" do
- allow(@provider).to receive(:release_path).and_return("/my/deploy/dir/releases/3")
- all_releases = ["/my/deploy/dir/releases/1", "/my/deploy/dir/releases/2", "/my/deploy/dir/releases/3", "/my/deploy/dir/releases/4", "/my/deploy/dir/releases/5"]
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect(@provider).to receive(:symlink)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/releases/4")
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/releases/5")
- @provider.run_action(:rollback)
- expect(@provider.release_path).to eql("/my/deploy/dir/releases/3")
- expect(@provider.shared_path).to eql("/my/deploy/dir/shared")
- end
-
- it "sets the release path to the specified release, symlinks, and rm's any newer releases on rollback" do
- allow(@provider).to receive(:release_path).and_call_original
- all_releases = ["/my/deploy/dir/releases/20040815162342", "/my/deploy/dir/releases/20040700000000",
- "/my/deploy/dir/releases/20040600000000", "/my/deploy/dir/releases/20040500000000"].sort!
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect(@provider).to receive(:symlink)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/releases/20040815162342")
- @provider.run_action(:rollback)
- expect(@provider.release_path).to eql("/my/deploy/dir/releases/20040700000000")
- expect(@provider.shared_path).to eql("/my/deploy/dir/shared")
- end
-
- it "sets the release path to the penultimate release, symlinks, and rm's the last release on rollback" do
- allow(@provider).to receive(:release_path).and_call_original
- all_releases = [ "/my/deploy/dir/releases/20040815162342",
- "/my/deploy/dir/releases/20040700000000",
- "/my/deploy/dir/releases/20040600000000",
- "/my/deploy/dir/releases/20040500000000"]
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect(@provider).to receive(:symlink)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/releases/20040815162342")
- @provider.run_action(:rollback)
- expect(@provider.release_path).to eql("/my/deploy/dir/releases/20040700000000")
- expect(@provider.shared_path).to eql("/my/deploy/dir/shared")
- 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"]
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- #@provider.should_receive(:symlink)
- #FileUtils.should_receive(:rm_rf).with("/my/deploy/dir/releases/20040815162342")
- #@provider.run_action(:rollback)
- #@provider.release_path.should eql(NIL) -- no check needed since assertions will fail
- expect do
- @provider.run_action(:rollback)
- end.to raise_exception(RuntimeError, "There is no release to rollback to!")
- end
-
- it "an exception is raised when there are no releases" do
- all_releases = []
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect do
- @provider.run_action(:rollback)
- end.to raise_exception(RuntimeError, "There is no release to rollback to!")
- end
- end
- end
-
- describe "CHEF-628: on systems with broken Dir.glob results" do
- it "sets the release path to the penultimate release, symlinks, and rm's the last release on rollback" do
- allow(@provider).to receive(:release_path).and_call_original
- all_releases = [ "/my/deploy/dir/releases/20040500000000",
- "/my/deploy/dir/releases/20040600000000",
- "/my/deploy/dir/releases/20040700000000",
- "/my/deploy/dir/releases/20040815162342" ]
- allow(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect(@provider).to receive(:symlink)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/releases/20040815162342")
- @provider.run_action(:rollback)
- expect(@provider.release_path).to eql("/my/deploy/dir/releases/20040700000000")
- expect(@provider.shared_path).to eql("/my/deploy/dir/shared")
- end
- end
-
- 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)
- end
-
- it "runs the new resource collection in the runner during a callback" do
- @runner = double("Runner")
- allow(Chef::Runner).to receive(:new).and_return(@runner)
- expect(@runner).to receive(:converge)
- callback_code = Proc.new { :noop }
- @provider.callback(:whatevs, callback_code)
- end
-
- it "loads callback files from the release/ dir if the file exists" do
- foo_callback = @expected_release_dir + "/deploy/foo.rb"
- expect(::File).to receive(:exist?).with(foo_callback).once.and_return(true)
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).and_yield
- expect(@provider).to receive(:from_file).with(foo_callback)
- @provider.callback(:foo, "deploy/foo.rb")
- end
-
- it "raises a runtime error if a callback file is explicitly specified but does not exist" do
- baz_callback = "/deploy/baz.rb"
- expect(::File).to receive(:exist?).with("#{@expected_release_dir}/#{baz_callback}").and_return(false)
- @resource.before_migrate baz_callback
- @provider.define_resource_requirements
- @provider.action = :deploy
- expect { @provider.process_resource_requirements }.to raise_error(RuntimeError)
- end
-
- it "runs a default callback if the callback code is nil" do
- bar_callback = @expected_release_dir + "/deploy/bar.rb"
- expect(::File).to receive(:exist?).with(bar_callback).and_return(true)
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).and_yield
- expect(@provider).to receive(:from_file).with(bar_callback)
- @provider.callback(:bar, nil)
- end
-
- it "skips an eval callback if the file doesn't exist" do
- barbaz_callback = @expected_release_dir + "/deploy/barbaz.rb"
- expect(::File).to receive(:exist?).with(barbaz_callback).and_return(false)
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).and_yield
- expect(@provider).not_to receive(:from_file)
- @provider.callback(:barbaz, nil)
- end
-
- # CHEF-3449 #converge_by is called in #recipe_eval and must happen in sequence
- # with the other calls to #converge_by to keep the train on the tracks
- it "evaluates a callback file before the corresponding step" do
- expect(@provider).to receive(:verify_directories_exist)
- expect(@provider).to receive(:update_cached_repo)
- expect(@provider).to receive(:enforce_ownership)
- expect(@provider).to receive(:copy_cached_repo)
- expect(@provider).to receive(:install_gems)
- expect(@provider).to receive(:enforce_ownership)
- expect(@provider).to receive(:converge_by).ordered # before_migrate
- expect(@provider).to receive(:migrate).ordered
- expect(@provider).to receive(:converge_by).ordered # before_symlink
- expect(@provider).to receive(:symlink).ordered
- expect(@provider).to receive(:converge_by).ordered # before_restart
- expect(@provider).to receive(:restart).ordered
- expect(@provider).to receive(:converge_by).ordered # after_restart
- expect(@provider).to receive(:cleanup!)
- @provider.deploy
- end
-
- it "gets a SCM provider as specified by its resource" do
- expect(@provider.scm_provider).to be_an_instance_of(Chef::Provider::Git)
- expect(@provider.scm_provider.new_resource.destination).to eql("/my/deploy/dir/shared/cached-copy")
- end
-
- it "syncs the cached copy of the repo" do
- expect(@provider.scm_provider).to receive(:run_action).with(:sync)
- @provider.update_cached_repo
- end
-
- it "makes a copy of the cached repo in releases dir" do
- expect(FileUtils).to receive(:mkdir_p).with("/my/deploy/dir/releases")
- expect(FileUtils).to receive(:cp_r).with("/my/deploy/dir/shared/cached-copy/.", @expected_release_dir, :preserve => true)
- @provider.copy_cached_repo
- end
-
- it "calls the internal callback :release_created when cleaning up the releases" do
- allow(FileUtils).to receive(:mkdir_p)
- allow(FileUtils).to receive(:cp_r)
- expect(@provider).to receive(:release_created)
- @provider.cleanup!
- end
-
- it "chowns the whole release dir to user and group specified in the resource" do
- @resource.user "foo"
- @resource.group "bar"
- expect(FileUtils).to receive(:chown_R).with("foo", "bar", "/my/deploy/dir", { :force => true })
- @provider.enforce_ownership
- end
-
- it "skips the migration when resource.migrate => false but runs symlinks before migration" do
- @resource.migrate false
- expect(@provider).not_to receive :shell_out!
- expect(@provider).to receive :run_symlinks_before_migrate
- @provider.migrate
- end
-
- it "links the database.yml and runs resource.migration_command when resource.migrate #=> true" do
- @resource.migrate true
- @resource.migration_command "migration_foo"
- @resource.user "deployNinja"
- @resource.group "deployNinjas"
- @resource.environment "RAILS_ENV" => "production"
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/config/database.yml", @expected_release_dir + "/config/database.yml")
- expect(@provider).to receive(:enforce_ownership)
-
- 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" })
- @provider.migrate
- end
-
- it "purges the current release's /log /tmp/pids/ and /public/system directories" do
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir + "/log")
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir + "/tmp/pids")
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir + "/public/system")
- @provider.purge_tempfiles_from_current_release
- end
-
- it "symlinks temporary files and logs from the shared dir into the current release" do
- allow(FileUtils).to receive(:mkdir_p).with(@resource.shared_path + "/system")
- allow(FileUtils).to receive(:mkdir_p).with(@resource.shared_path + "/pids")
- allow(FileUtils).to receive(:mkdir_p).with(@resource.shared_path + "/log")
- expect(FileUtils).to receive(:mkdir_p).with(@expected_release_dir + "/tmp")
- expect(FileUtils).to receive(:mkdir_p).with(@expected_release_dir + "/public")
- expect(FileUtils).to receive(:mkdir_p).with(@expected_release_dir + "/config")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/system", @expected_release_dir + "/public/system")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/pids", @expected_release_dir + "/tmp/pids")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/log", @expected_release_dir + "/log")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/config/database.yml", @expected_release_dir + "/config/database.yml")
- expect(@provider).to receive(:enforce_ownership)
- @provider.link_tempfiles_to_current_release
- end
-
- it "symlinks the current release dir into production" do
- expect(FileUtils).to receive(:rm_f).with("/my/deploy/dir/current")
- expect(FileUtils).to receive(:ln_sf).with(@expected_release_dir, "/my/deploy/dir/current")
- expect(@provider).to receive(:enforce_ownership)
- @provider.link_current_release_to_production
- 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})
- @resource.symlinks "foo/bar" => "foo/bar", "baz" => "qux/baz"
- @resource.symlink_before_migrate "radiohead/in_rainbows.yml" => "awesome"
- end
-
- it "purges the purge_before_symlink directories" do
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir + "/foo")
- expect(FileUtils).to receive(:rm_rf).with(@expected_release_dir + "/bar")
- @provider.purge_tempfiles_from_current_release
- end
-
- it "symlinks files from the shared directory to the current release directory" do
- expect(FileUtils).to receive(:mkdir_p).with(@expected_release_dir + "/baz")
- expect(FileUtils).to receive(:mkdir_p).with(@expected_release_dir + "/qux")
- allow(FileUtils).to receive(:mkdir_p).with(@resource.shared_path + "/foo/bar")
- allow(FileUtils).to receive(:mkdir_p).with(@resource.shared_path + "/baz")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/foo/bar", @expected_release_dir + "/foo/bar")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/baz", @expected_release_dir + "/qux/baz")
- expect(FileUtils).to receive(:ln_sf).with("/my/deploy/dir/shared/radiohead/in_rainbows.yml", @expected_release_dir + "/awesome")
- 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
- expect(@provider).not_to receive(:shell_out!)
- @provider.restart
- end
-
- it "runs the restart command in the current application dir when the resource has a restart_command" do
- @resource.restart_command "restartcmd"
- expect(@provider).to receive(:shell_out!).with("restartcmd", :cwd => "/my/deploy/dir/current", :log_tag => "deploy[/my/deploy/dir]", :log_level => :debug)
- @provider.restart
- end
-
- it "lists all available releases" do
- all_releases = ["/my/deploy/dir/20040815162342", "/my/deploy/dir/20040700000000",
- "/my/deploy/dir/20040600000000", "/my/deploy/dir/20040500000000"].sort!
- expect(Dir).to receive(:glob).with("/my/deploy/dir/releases/*").and_return(all_releases)
- expect(@provider.all_releases).to eql(all_releases)
- end
-
- it "removes all but the 5 newest releases" do
- all_releases = ["/my/deploy/dir/20040815162342", "/my/deploy/dir/20040700000000",
- "/my/deploy/dir/20040600000000", "/my/deploy/dir/20040500000000",
- "/my/deploy/dir/20040400000000", "/my/deploy/dir/20040300000000",
- "/my/deploy/dir/20040200000000", "/my/deploy/dir/20040100000000"].sort!
- allow(@provider).to receive(:all_releases).and_return(all_releases)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/20040100000000")
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/20040200000000")
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/20040300000000")
- @provider.cleanup!
- end
-
- it "removes all but a certain number of releases when the resource has a keep_releases" do
- @resource.keep_releases 7
- all_releases = ["/my/deploy/dir/20040815162342", "/my/deploy/dir/20040700000000",
- "/my/deploy/dir/20040600000000", "/my/deploy/dir/20040500000000",
- "/my/deploy/dir/20040400000000", "/my/deploy/dir/20040300000000",
- "/my/deploy/dir/20040200000000", "/my/deploy/dir/20040100000000"].sort!
- allow(@provider).to receive(:all_releases).and_return(all_releases)
- expect(FileUtils).to receive(:rm_rf).with("/my/deploy/dir/20040100000000")
- @provider.cleanup!
- end
-
- it "fires a callback for :release_deleted when deleting an old release" do
- all_releases = ["/my/deploy/dir/20040815162342", "/my/deploy/dir/20040700000000",
- "/my/deploy/dir/20040600000000", "/my/deploy/dir/20040500000000",
- "/my/deploy/dir/20040400000000", "/my/deploy/dir/20040300000000"].sort!
- allow(@provider).to receive(:all_releases).and_return(all_releases)
- allow(FileUtils).to receive(:rm_rf)
- expect(@provider).to receive(:release_deleted).with("/my/deploy/dir/20040300000000")
- @provider.cleanup!
- end
-
- it "puts resource.to_hash in @configuration for backwards compat with capistano-esque deploy hooks" do
- expect(@provider.instance_variable_get(:@configuration)).to eq(@resource.to_hash)
- end
-
- it "sets @configuration[:environment] to the value of RAILS_ENV for backwards compat reasons" do
- resource = Chef::Resource::Deploy.new("/my/deploy/dir")
- resource.environment "production"
- provider = Chef::Provider::Deploy.new(resource, @run_context)
- expect(provider.instance_variable_get(:@configuration)[:environment]).to eql("production")
- end
-
- it "shouldn't give a no method error on migrate if the environment is nil" do
- allow(@provider).to receive(:enforce_ownership)
- 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 }
- #@provider.should_receive(:instance_eval).with(&recipe_code)
- @provider.callback(:whateverz, recipe_code)
- expect(snitch).to eq(42)
- end
-
- it "loads a recipe file from the specified path and from_file evals it" do
- expect(::File).to receive(:exist?).with(@expected_release_dir + "/chefz/foobar_callback.rb").once.and_return(true)
- expect(::Dir).to receive(:chdir).with(@expected_release_dir).and_yield
- expect(@provider).to receive(:from_file).with(@expected_release_dir + "/chefz/foobar_callback.rb")
- @provider.callback(:whateverz, "chefz/foobar_callback.rb")
- end
-
- it "instance_evals a block/proc for restart command" do
- snitch = nil
- 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
- it "defines sudo as a forwarder to execute" do
- expect(@provider).to receive(:execute).with("the moon, fool")
- @provider.sudo("the moon, fool")
- end
-
- it "defines run as a forwarder to execute, setting the user, group, cwd and environment to new_resource.user" do
- mock_execution = double("Resource::Execute")
- expect(@provider).to receive(:execute).with("iGoToHell4this").and_return(mock_execution)
- @resource.user("notCoolMan")
- @resource.group("Ggroup")
- @resource.environment("APP_ENV" => "staging")
- @resource.deploy_to("/my/app")
- expect(mock_execution).to receive(:user).with("notCoolMan")
- expect(mock_execution).to receive(:group).with("Ggroup")
- expect(mock_execution).to receive(:cwd) { |*args|
- if args.empty?
- nil
- else
- expect(args.size).to eq(1)
- expect(args.first).to eq(@provider.release_path)
- end
- }.twice
- expect(mock_execution).to receive(:environment) { |*args|
- if args.empty?
- nil
- else
- expect(args.size).to eq(1)
- 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
- mock_execution = double("Resource::Execute")
- expect(@provider).to receive(:execute).with("iGoToHell4this").and_return(mock_execution)
- @resource.user("notCoolMan")
- expect(mock_execution).to receive(:user).with("notCoolMan")
- expect(mock_execution).to receive(:cwd).with(no_args()).and_return("/some/value")
- expect(mock_execution).to receive(:environment).with(no_args()).and_return({})
- @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)
-
- snitch = nil
- @resource.user("tehCat")
-
- callback_code = Proc.new do
- snitch = 42
- temp_collection = resource_collection
- run("tehMice")
- snitch = temp_collection.lookup("execute[tehMice]")
- end
-
- expect(runner).to receive(:converge)
- #
- @provider.callback(:phony, callback_code)
- expect(snitch).to be_an_instance_of(Chef::Resource::Execute)
- expect(snitch.user).to eq("tehCat")
- end
- 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" }]
- end
-
- it "reads a gems.yml file, creating gem providers for each with action :upgrade" do
- expect(IO).to receive(:read).with("#{@expected_release_dir}/gems.yml").and_return("cookie")
- expect(YAML).to receive(:load).with("cookie").and_return(@gem_list)
-
- gems = @provider.send(:gem_packages)
-
- expect(gems.map { |g| g.action }).to eq([%i{install}])
- expect(gems.map { |g| g.name }).to eq(%w{eventmachine})
- expect(gems.map { |g| g.version }).to eq(%w{0.12.9})
- end
-
- it "takes a list of gem providers converges them" do
- allow(IO).to receive(:read)
- allow(YAML).to receive(:load).and_return(@gem_list)
- expected_gem_resources = @provider.send(:gem_packages).map { |r| [r.name, r.version] }
- gem_runner = @provider.send(:gem_resource_collection_runner)
- # no one has heard of defining == to be meaningful so I have use this monstrosity
- 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/dsc_resource_spec.rb b/spec/unit/provider/dsc_resource_spec.rb
index 747e37f308..411dc50cc9 100644
--- a/spec/unit/provider/dsc_resource_spec.rb
+++ b/spec/unit/provider/dsc_resource_spec.rb
@@ -103,8 +103,8 @@ describe Chef::Provider::DscResource do
it "flags the resource as reboot required when required" do
expect(provider).to receive(:test_resource).and_return(false)
- expect(provider).to receive(:invoke_resource).
- and_return(double(:stdout => "", :return_value => nil))
+ expect(provider).to receive(:invoke_resource)
+ .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)
@@ -113,8 +113,8 @@ describe Chef::Provider::DscResource do
it "does not flag the resource as reboot required when not required" do
expect(provider).to receive(:test_resource).and_return(false)
- expect(provider).to receive(:invoke_resource).
- and_return(double(:stdout => "", :return_value => nil))
+ expect(provider).to receive(:invoke_resource)
+ .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)
@@ -293,12 +293,12 @@ describe Chef::Provider::DscResource do
set_node_object
end
- let(:cmdlet) { double(:run! => nil) }
+ let(:cmdlet) { double(run!: nil) }
before(:each) do
allow(provider).to receive(:translate_type).and_return("my_properties")
provider.instance_variable_set(:@new_resource, double(
- :properties => "my_properties", :resource => "my_resource", :timeout => 123
+ properties: "my_properties", resource: "my_resource", timeout: 123
))
end
diff --git a/spec/unit/provider/env/windows_spec.rb b/spec/unit/provider/env/windows_spec.rb
deleted file mode 100644
index 5ddc1d6f91..0000000000
--- a/spec/unit/provider/env/windows_spec.rb
+++ /dev/null
@@ -1,103 +0,0 @@
-#
-# Author:: Sander van Harmelen <svanharmelen@schubergphilis.com>
-# Copyright:: Copyright 2014-2016, Chef Software, Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Provider::Env::Windows, :windows_only do
- let(:node) { Chef::Node.new }
- let(:events) { Chef::EventDispatch::Dispatcher.new }
- let(:run_context) { Chef::RunContext.new(node, {}, events) }
-
- context "when environment variable is not PATH" do
- let(:new_resource) do
- new_resource = Chef::Resource::Env.new("CHEF_WINDOWS_ENV_TEST")
- new_resource.value("foo")
- new_resource
- end
- let(:provider) do
- 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
- end
-
- describe "action_create" do
- before do
- ENV.delete("CHEF_WINDOWS_ENV_TEST")
- provider.key_exists = false
- end
-
- it "should update the ruby ENV object when it creates the key" do
- provider.action_create
- expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql("foo")
- end
- end
-
- describe "action_modify" do
- before do
- ENV["CHEF_WINDOWS_ENV_TEST"] = "foo"
- end
-
- it "should update the ruby ENV object when it updates the value" do
- expect(provider).to receive(:requires_modify_or_create?).and_return(true)
- new_resource.value("foobar")
- provider.action_modify
- expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql("foobar")
- end
-
- describe "action_delete" do
- before do
- ENV["CHEF_WINDOWS_ENV_TEST"] = "foo"
- end
-
- it "should update the ruby ENV object when it deletes the key" do
- provider.action_delete
- expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql(nil)
- end
- end
- end
- end
-
- context "when environment is PATH" do
- describe "for PATH" do
- let(:system_root) { "%SystemRoot%" }
- let(:system_root_value) { 'D:\Windows' }
- let(:new_resource) do
- new_resource = Chef::Resource::Env.new("PATH")
- new_resource.value(system_root)
- new_resource
- end
- let(:provider) do
- 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
- end
-
- before do
- stub_const("ENV", { "PATH" => "" })
- end
-
- it "replaces Windows system variables" do
- expect(provider).to receive(:requires_modify_or_create?).and_return(true)
- expect(provider).to receive(:expand_path).with(system_root).and_return(system_root_value)
- provider.action_modify
- expect(ENV["PATH"]).to eql(system_root_value)
- end
- end
-
- end
-end
diff --git a/spec/unit/provider/erl_call_spec.rb b/spec/unit/provider/erl_call_spec.rb
deleted file mode 100644
index b5d3ae8c07..0000000000
--- a/spec/unit/provider/erl_call_spec.rb
+++ /dev/null
@@ -1,77 +0,0 @@
-#
-# Author:: Joe Williams (<joe@joetify.com>)
-# Copyright:: Copyright 2009-2016, Joe Williams
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Provider::ErlCall do
- before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
-
- @new_resource = Chef::Resource::ErlCall.new("test", @node)
- @new_resource.code("io:format(\"burritos\", []).")
- @new_resource.node_name("chef@localhost")
- @new_resource.name("test")
-
- @provider = Chef::Provider::ErlCall.new(@new_resource, @run_context)
-
- @status = double("Status", stdout: "{ok, woohoo}", stderr: "")
- allow(@provider).to receive(:shell_out!).and_return(@status)
- end
-
- it "should return a Chef::Provider::ErlCall object" do
- provider = Chef::Provider::ErlCall.new(@new_resource, @run_context)
- expect(provider).to be_a_kind_of(Chef::Provider::ErlCall)
- end
-
- it "should return true" do
- expect(@provider.load_current_resource).to eql(true)
- end
-
- describe "when running a distributed erl call resource" do
- before do
- @new_resource.cookie("nomnomnom")
- @new_resource.distributed(true)
- @new_resource.name_type("sname")
- end
-
- it "should write to stdin of the erl_call command" do
- expected_cmd = "erl_call -e -s -sname chef@localhost -c nomnomnom"
- expect(@provider).to receive(:shell_out!).with(expected_cmd, input: @new_resource.code).and_return(@status)
-
- @provider.action_run
- end
- end
-
- describe "when running a local erl call resource" do
- before do
- @new_resource.cookie(nil)
- @new_resource.distributed(false)
- @new_resource.name_type("name")
- end
-
- it "should write to stdin of the erl_call command" do
- expected_cmd = "erl_call -e -name chef@localhost "
- expect(@provider).to receive(:shell_out!).with(expected_cmd, input: @new_resource.code).and_return(@status)
-
- @provider.action_run
- end
- end
-
-end
diff --git a/spec/unit/provider/execute_spec.rb b/spec/unit/provider/execute_spec.rb
index 58cb9f33a8..622d54af37 100644
--- a/spec/unit/provider/execute_spec.rb
+++ b/spec/unit/provider/execute_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Prajakta Purohit (<prajakta@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,13 +26,14 @@ describe Chef::Provider::Execute do
let(:provider) { Chef::Provider::Execute.new(new_resource, run_context) }
let(:current_resource) { Chef::Resource::Ifconfig.new("foo_resource", run_context) }
# You will be the same object, I promise.
- @live_stream = Chef::EventDispatch::EventsOutputStream.new(run_context.events, :name => :execute)
+ @live_stream = Chef::EventDispatch::EventsOutputStream.new(run_context.events, name: :execute)
let(:opts) do
{
timeout: 3600,
returns: 0,
log_level: :info,
+ default_env: false,
log_tag: new_resource.to_s,
}
end
@@ -76,7 +77,7 @@ describe Chef::Provider::Execute do
describe "#action_run" do
it "runs shell_out with the default options" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute foo_resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -101,9 +102,9 @@ describe Chef::Provider::Execute do
expect(new_resource).to be_updated
end
- it "if you pass a command attribute, it runs the command" do
+ it "if you pass a command property, it runs the command" do
new_resource.command "/usr/argelbargle/bin/oogachacka 12345"
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.command, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.command, opts)
expect(provider).to receive(:converge_by).with("execute #{new_resource.command}").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -114,7 +115,7 @@ describe Chef::Provider::Execute do
new_resource.sensitive true
# Since the resource is sensitive, it should not have :live_stream set
opts.delete(:live_stream)
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute sensitive resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -124,7 +125,7 @@ describe Chef::Provider::Execute do
it "should do nothing if the sentinel file exists" do
new_resource.creates "/foo_resource"
expect(FileTest).to receive(:exist?).with(new_resource.creates).and_return(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out!)
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
expect(new_resource).not_to be_updated
@@ -137,7 +138,7 @@ describe Chef::Provider::Execute do
end
it "should raise if user specified relative path without cwd for Chef-13" do
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out!)
expect { provider.run_action(:run) }.to raise_error(Chef::Exceptions::Execute)
end
end
@@ -148,7 +149,7 @@ describe Chef::Provider::Execute do
expect(FileTest).not_to receive(:exist?).with(new_resource.creates)
expect(FileTest).to receive(:exist?).with(File.join("/tmp", new_resource.creates)).and_return(true)
expect(Chef::Log).not_to receive(:warn)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out!)
provider.run_action(:run)
expect(new_resource).not_to be_updated
@@ -157,7 +158,7 @@ describe Chef::Provider::Execute do
it "should not include stdout/stderr in failure exception for sensitive resource" do
opts.delete(:live_stream)
new_resource.sensitive true
- expect(provider).to receive(:shell_out_with_systems_locale!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
+ expect(provider).to receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
expect do
provider.run_action(:run)
end.to raise_error(Mixlib::ShellOut::ShellCommandFailed, /suppressed for sensitive resource/)
@@ -166,7 +167,7 @@ describe Chef::Provider::Execute do
describe "streaming output" do
it "should not set the live_stream if sensitive is on" do
new_resource.sensitive true
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute sensitive resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -183,7 +184,7 @@ describe Chef::Provider::Execute do
it "should set the live_stream if the log level is info or above" do
nopts = opts
nopts[:live_stream] = @live_stream
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, nopts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, nopts)
expect(provider).to receive(:converge_by).with("execute foo_resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -195,7 +196,7 @@ describe Chef::Provider::Execute do
new_resource.live_stream true
nopts = opts
nopts[:live_stream] = @live_stream
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, nopts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, nopts)
expect(provider).to receive(:converge_by).with("execute foo_resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -204,7 +205,7 @@ describe Chef::Provider::Execute do
it "should not set the live_stream if the resource is sensitive" do
new_resource.sensitive true
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute sensitive resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -217,7 +218,7 @@ describe Chef::Provider::Execute do
nopts = opts
nopts[:live_stream] = STDOUT
allow(STDOUT).to receive(:tty?).and_return(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, nopts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, nopts)
expect(provider).to receive(:converge_by).with("execute foo_resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -227,7 +228,7 @@ describe Chef::Provider::Execute do
it "should not set the live_stream to STDOUT if we are a TTY, not daemonized, but sensitive" do
new_resource.sensitive true
allow(STDOUT).to receive(:tty?).and_return(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute sensitive resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
@@ -237,7 +238,7 @@ describe Chef::Provider::Execute do
it "should not set the live_stream to STDOUT if we are a TTY, but daemonized" do
Chef::Config[:daemon] = true
allow(STDOUT).to receive(:tty?).and_return(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with(new_resource.name, opts)
+ expect(provider).to receive(:shell_out!).with(new_resource.name, opts)
expect(provider).to receive(:converge_by).with("execute foo_resource").and_call_original
expect(Chef::Log).not_to receive(:warn)
provider.run_action(:run)
diff --git a/spec/unit/provider/file/content_spec.rb b/spec/unit/provider/file/content_spec.rb
index f840d92dbb..e65d094327 100644
--- a/spec/unit/provider/file/content_spec.rb
+++ b/spec/unit/provider/file/content_spec.rb
@@ -36,7 +36,7 @@ describe Chef::Provider::File::Content do
end
let(:new_resource) do
- double("Chef::Provider::File::Resource (new)", :name => "seattle.txt", :path => resource_path)
+ double("Chef::Provider::File::Resource (new)", name: "seattle.txt", path: resource_path)
end
let(:run_context) do
diff --git a/spec/unit/provider/file_spec.rb b/spec/unit/provider/file_spec.rb
index d8d4ed2286..311ef4c55a 100644
--- a/spec/unit/provider/file_spec.rb
+++ b/spec/unit/provider/file_spec.rb
@@ -34,7 +34,8 @@ describe Chef::Provider::File do
let(:node) { double("Chef::Node") }
let(:events) { double("Chef::Events").as_null_object } # mock all the methods
- let(:run_context) { double("Chef::RunContext", :node => node, :events => events) }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
let(:enclosing_directory) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
diff --git a/spec/unit/provider/git_spec.rb b/spec/unit/provider/git_spec.rb
index cacee0baaa..4a6266b58a 100644
--- a/spec/unit/provider/git_spec.rb
+++ b/spec/unit/provider/git_spec.rb
@@ -58,7 +58,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], :log_tag => "git[web2.0 app]" }).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], log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout))
expect(@provider.find_current_revision).to eql("9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13")
end
@@ -66,7 +66,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], :log_tag => "git[web2.0 app]" ).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], log_tag: "git[web2.0 app]" ).and_return(double("ShellOut result", stdout: "", stderr: @stderr))
expect(@provider.find_current_revision).to be_nil
end
end
@@ -152,7 +152,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
@@ -161,7 +161,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
@@ -170,7 +170,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
@@ -179,7 +179,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
@@ -188,7 +188,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
@@ -198,7 +198,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
@@ -207,7 +207,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
@@ -222,21 +222,21 @@ describe Chef::Provider::Git do
it "raises an unresolvable git reference error if the revision can't be resolved to any revision and assertions are run" do
@resource.revision "FAIL, that's the revision I want"
@provider.action = :checkout
- expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", :stdout => "\n"))
+ expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", stdout: "\n"))
@provider.define_resource_requirements
expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::UnresolvableGitReference)
end
it "does not raise an error if the revision can't be resolved when assertions are not run" do
@resource.revision "FAIL, that's the revision I want"
- expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", :stdout => "\n"))
+ expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", stdout: "\n"))
expect(@provider.target_revision).to eq(nil)
end
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
@@ -244,24 +244,24 @@ describe Chef::Provider::Git do
end
it "gives the latest HEAD revision SHA if nothing is specified" do
- @stdout = <<-SHAS
-28af684d8460ba4793eda3e7ac238c864a5d029a\tHEAD
-503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha
-28af684d8460ba4793eda3e7ac238c864a5d029a\trefs/heads/master
-c44fe79bb5e36941ce799cee6b9de3a2ef89afee\trefs/tags/0.5.2
-14534f0e0bf133dc9ff6dbe74f8a0c863ff3ac6d\trefs/tags/0.5.4
-d36fddb4291341a1ff2ecc3c560494e398881354\trefs/tags/0.5.6
-9e5ce9031cbee81015de680d010b603bce2dd15f\trefs/tags/0.6.0
-9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\trefs/tags/0.6.2
-014a69af1cdce619de82afaf6cdb4e6ac658fede\trefs/tags/0.7.0
-fa8097ff666af3ce64761d8e1f1c2aa292a11378\trefs/tags/0.7.2
-44f9be0b33ba5c10027ddb030a5b2f0faa3eeb8d\trefs/tags/0.7.4
-d7b9957f67236fa54e660cc3ab45ffecd6e0ba38\trefs/tags/0.7.8
-b7d19519a1c15f1c1a324e2683bd728b6198ce5a\trefs/tags/0.7.8^{}
-ebc1b392fe7e8f0fbabc305c299b4d365d2b4d9b\trefs/tags/chef-server-package
+ @stdout = <<~SHAS
+ 28af684d8460ba4793eda3e7ac238c864a5d029a\tHEAD
+ 503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha
+ 28af684d8460ba4793eda3e7ac238c864a5d029a\trefs/heads/master
+ c44fe79bb5e36941ce799cee6b9de3a2ef89afee\trefs/tags/0.5.2
+ 14534f0e0bf133dc9ff6dbe74f8a0c863ff3ac6d\trefs/tags/0.5.4
+ d36fddb4291341a1ff2ecc3c560494e398881354\trefs/tags/0.5.6
+ 9e5ce9031cbee81015de680d010b603bce2dd15f\trefs/tags/0.6.0
+ 9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\trefs/tags/0.6.2
+ 014a69af1cdce619de82afaf6cdb4e6ac658fede\trefs/tags/0.7.0
+ fa8097ff666af3ce64761d8e1f1c2aa292a11378\trefs/tags/0.7.2
+ 44f9be0b33ba5c10027ddb030a5b2f0faa3eeb8d\trefs/tags/0.7.4
+ d7b9957f67236fa54e660cc3ab45ffecd6e0ba38\trefs/tags/0.7.8
+ 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
@@ -276,15 +276,15 @@ SHAS
let(:expected_cmd) { 'git clone "git://github.com/opscode/chef.git" "/my/deploy/dir"' }
let(:default_options) do
{
- :user => deploy_user,
- :environment => { "GIT_SSH" => wrapper, "HOME" => "/home/deployNinja" },
- :log_tag => "git[web2.0 app]",
+ user: deploy_user,
+ environment: { "GIT_SSH" => wrapper, "HOME" => "/home/deployNinja" },
+ log_tag: "git[web2.0 app]",
}
end
before do
@resource.user deploy_user
@resource.ssh_wrapper wrapper
- allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/deployNinja"))
+ allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja"))
end
context "without a timeout set" do
it "clones a repo with default git options" do
@@ -296,7 +296,7 @@ SHAS
let (:seconds) { 10 }
before { @resource.timeout(seconds) }
it "clones a repo with amended git options" do
- expect(@provider).to receive(:shell_out!).with(expected_cmd, default_options.merge(:timeout => seconds))
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, default_options.merge(timeout: seconds))
@provider.clone
end
end
@@ -306,9 +306,9 @@ SHAS
end
let(:overrided_options) do
{
- :user => deploy_user,
- :environment => { "GIT_SSH" => wrapper, "HOME" => "/home/masterNinja" },
- :log_tag => "git[web2.0 app]",
+ user: deploy_user,
+ environment: { "GIT_SSH" => wrapper, "HOME" => "/home/masterNinja" },
+ log_tag: "git[web2.0 app]",
}
end
before do
@@ -327,14 +327,14 @@ SHAS
let(:expected_cmd) { 'git clone "git://github.com/opscode/chef.git" "/my/deploy/dir"' }
let(:default_options) do
{
- :user => 123,
- :environment => { "HOME" => "/home/deployNinja" },
- :log_tag => "git[web2.0 app]",
+ user: 123,
+ environment: { "HOME" => "/home/deployNinja" },
+ log_tag: "git[web2.0 app]",
}
end
before do
@resource.user deploy_user
- allow(Etc).to receive(:getpwuid).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/deployNinja"))
+ allow(Etc).to receive(:getpwuid).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja"))
end
context "with a specific home" do
let (:override_home) do
@@ -342,9 +342,9 @@ SHAS
end
let(:overrided_options) do
{
- :user => 123,
- :environment => { "HOME" => "/home/masterNinja" },
- :log_tag => "git[web2.0 app]",
+ user: 123,
+ environment: { "HOME" => "/home/masterNinja" },
+ log_tag: "git[web2.0 app]",
}
end
before do
@@ -360,14 +360,14 @@ SHAS
it "runs a clone command with escaped destination" do
@resource.user "deployNinja"
- allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/deployNinja"))
+ allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja"))
@resource.destination "/Application Support/with/space"
@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",
- :log_tag => "git[web2.0 app]",
- :environment => { "HOME" => "/home/deployNinja",
- "GIT_SSH" => "do_it_this_way.sh" })
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, user: "deployNinja",
+ log_tag: "git[web2.0 app]",
+ environment: { "HOME" => "/home/deployNinja",
+ "GIT_SSH" => "do_it_this_way.sh" })
@provider.clone
end
@@ -377,8 +377,8 @@ SHAS
version_response = double("shell_out")
allow(version_response).to receive(:stdout) { "git version 1.7.9" }
expect(@provider).to receive(:shell_out!).with("git --version",
- :log_tag => "git[web2.0 app]").and_return(version_response)
- expect(@provider).to receive(:shell_out!).with(expected_cmd, :log_tag => "git[web2.0 app]")
+ log_tag: "git[web2.0 app]").and_return(version_response)
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]")
@provider.clone
end
@@ -388,33 +388,33 @@ SHAS
version_response = double("shell_out")
allow(version_response).to receive(:stdout) { "git version 1.7.10" }
expect(@provider).to receive(:shell_out!).with("git --version",
- :log_tag => "git[web2.0 app]").and_return(version_response)
- expect(@provider).to receive(:shell_out!).with(expected_cmd, :log_tag => "git[web2.0 app]")
+ log_tag: "git[web2.0 app]").and_return(version_response)
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]")
@provider.clone
end
it "compiles a clone command with a remote other than ``origin''" do
@resource.remote "opscode"
expected_cmd = "git clone -o opscode \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\""
- expect(@provider).to receive(:shell_out!).with(expected_cmd, :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]")
@provider.clone
end
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
- expect(@provider).to receive(:shell_out!).with("git checkout deploy", :cwd => "/my/deploy/dir",
- :log_tag => "git[web2.0 app]").ordered
+ expect(@provider).to receive(:shell_out!).with("git branch -f deploy d35af14d41ae22b19da05d7d03a0bafc321b244c", cwd: "/my/deploy/dir",
+ 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
@provider.checkout
end
it "runs an enable_submodule command" do
@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]")
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, cwd: "/my/deploy/dir",
+ 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]")
+ expect(@provider).to receive(:shell_out!).with(expected_cmd, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
@provider.enable_submodules
end
@@ -425,60 +425,60 @@ SHAS
it "runs a sync command with default options" do
expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
- expected_cmd1 = "git fetch origin"
- expect(@provider).to receive(:shell_out!).with(expected_cmd1, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expected_cmd1 = "git fetch --prune origin"
+ expect(@provider).to receive(:shell_out!).with(expected_cmd1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
expected_cmd2 = "git fetch origin --tags"
- expect(@provider).to receive(:shell_out!).with(expected_cmd2, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(expected_cmd2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
expected_cmd3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
- expect(@provider).to receive(:shell_out!).with(expected_cmd3, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(expected_cmd3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
@provider.fetch_updates
end
it "runs a sync command with the user and group specified in the resource" do
@resource.user("whois")
- allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/whois"))
+ allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/whois"))
@resource.group("thisis")
expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
- expected_cmd1 = "git fetch origin"
- expect(@provider).to receive(:shell_out!).with(expected_cmd1, :cwd => "/my/deploy/dir",
- :user => "whois", :group => "thisis",
- :log_tag => "git[web2.0 app]",
- :environment => { "HOME" => "/home/whois" })
+ expected_cmd1 = "git fetch --prune origin"
+ expect(@provider).to receive(:shell_out!).with(expected_cmd1, cwd: "/my/deploy/dir",
+ user: "whois", group: "thisis",
+ log_tag: "git[web2.0 app]",
+ environment: { "HOME" => "/home/whois" })
expected_cmd2 = "git fetch origin --tags"
- expect(@provider).to receive(:shell_out!).with(expected_cmd2, :cwd => "/my/deploy/dir",
- :user => "whois", :group => "thisis",
- :log_tag => "git[web2.0 app]",
- :environment => { "HOME" => "/home/whois" })
+ expect(@provider).to receive(:shell_out!).with(expected_cmd2, cwd: "/my/deploy/dir",
+ user: "whois", group: "thisis",
+ log_tag: "git[web2.0 app]",
+ environment: { "HOME" => "/home/whois" })
expected_cmd3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
- expect(@provider).to receive(:shell_out!).with(expected_cmd3, :cwd => "/my/deploy/dir",
- :user => "whois", :group => "thisis",
- :log_tag => "git[web2.0 app]",
- :environment => { "HOME" => "/home/whois" })
+ expect(@provider).to receive(:shell_out!).with(expected_cmd3, cwd: "/my/deploy/dir",
+ user: "whois", group: "thisis",
+ log_tag: "git[web2.0 app]",
+ environment: { "HOME" => "/home/whois" })
@provider.fetch_updates
end
it "configures remote tracking branches when remote is ``origin''" do
@resource.remote "origin"
expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
- fetch_command1 = "git fetch origin"
- expect(@provider).to receive(:shell_out!).with(fetch_command1, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ fetch_command1 = "git fetch --prune origin"
+ expect(@provider).to receive(:shell_out!).with(fetch_command1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
fetch_command2 = "git fetch origin --tags"
- expect(@provider).to receive(:shell_out!).with(fetch_command2, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(fetch_command2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
fetch_command3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
- expect(@provider).to receive(:shell_out!).with(fetch_command3, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(fetch_command3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
@provider.fetch_updates
end
it "configures remote tracking branches when remote is not ``origin''" do
@resource.remote "opscode"
expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository)
- fetch_command1 = "git fetch opscode"
- expect(@provider).to receive(:shell_out!).with(fetch_command1, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ fetch_command1 = "git fetch --prune opscode"
+ expect(@provider).to receive(:shell_out!).with(fetch_command1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
fetch_command2 = "git fetch opscode --tags"
- expect(@provider).to receive(:shell_out!).with(fetch_command2, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(fetch_command2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
fetch_command3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c"
- expect(@provider).to receive(:shell_out!).with(fetch_command3, :cwd => "/my/deploy/dir", :log_tag => "git[web2.0 app]")
+ expect(@provider).to receive(:shell_out!).with(fetch_command3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]")
@provider.fetch_updates
end
@@ -489,37 +489,37 @@ SHAS
allow(command_response).to receive(:exitstatus) { 1 }
expected_command = "git config --get remote.#{@resource.remote}.url"
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)
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ 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]")
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]")
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
it "runs the config with the user and group specified in the resource" do
@resource.user("whois")
@resource.group("thisis")
- allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", :name => @resource.user, :dir => "/home/whois"))
+ allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/whois"))
command_response = double("shell_out")
allow(command_response).to receive(:exitstatus) { 1 }
expected_command = "git config --get remote.#{@resource.remote}.url"
expect(@provider).to receive(:shell_out!).with(expected_command,
- :cwd => "/my/deploy/dir",
- :log_tag => "git[web2.0 app]",
- :user => "whois",
- :group => "thisis",
- :environment => { "HOME" => "/home/whois" },
- :returns => [0, 1, 2]).and_return(command_response)
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ user: "whois",
+ group: "thisis",
+ 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" })
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ user: "whois",
+ group: "thisis",
+ environment: { "HOME" => "/home/whois" })
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
@@ -529,13 +529,13 @@ SHAS
allow(command_response).to receive(:exitstatus) { 1 }
check_remote_command = "git config --get remote.#{@resource.remote}.url"
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)
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ 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",
- :log_tag => "git[web2.0 app]")
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]")
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
end
@@ -547,13 +547,13 @@ SHAS
allow(command_response).to receive(:stdout) { "some_other_url" }
check_remote_command = "git config --get remote.#{@resource.remote}.url"
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)
- expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ 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",
- :log_tag => "git[web2.0 app]")
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]")
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
@@ -563,13 +563,13 @@ SHAS
allow(command_response).to receive(:stdout) { @resource.repository }
check_remote_command = "git config --get remote.#{@resource.remote}.url"
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)
- unexpected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ 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",
- :log_tag => "git[web2.0 app]")
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]")
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
@@ -578,13 +578,13 @@ SHAS
allow(command_response).to receive(:exitstatus) { 2 }
check_remote_command = "git config --get remote.#{@resource.remote}.url"
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)
- expected_command = "git config --replace-all remote.#{@resource.remote}.url #{@resource.repository}"
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]",
+ 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",
- :log_tag => "git[web2.0 app]")
+ cwd: "/my/deploy/dir",
+ log_tag: "git[web2.0 app]")
@provider.setup_remote_tracking_branches(@resource.remote, @resource.repository)
end
end
@@ -705,9 +705,9 @@ SHAS
allow(::File).to receive(:directory?).with("/my/deploy/dir").and_return(true)
allow(@provider).to receive(:sync_command).and_return("huzzah!")
expect(@provider).to receive(:action_checkout)
- expect(@provider).not_to receive(:shell_out!).with("huzzah!", :cwd => "/my/deploy/dir")
+ expect(@provider).not_to receive(:shell_out!).with("huzzah!", cwd: "/my/deploy/dir")
@provider.run_action(:sync)
- #@resource.should be_updated
+ # @resource.should be_updated
end
it "does an export by cloning the repo then removing the .git directory" do
@@ -719,8 +719,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 e25b77c051..8bd6485740 100644
--- a/spec/unit/provider/group/dscl_spec.rb
+++ b/spec/unit/provider/group/dscl_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Dreamcat4 (<dreamcat4@gmail.com>)
-# Copyright:: Copyright 2009-2016, Chef Software Inc.
+# Copyright:: Copyright 2009-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,21 +19,24 @@
require "spec_helper"
describe Chef::Provider::Group::Dscl do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
before do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@new_resource = Chef::Resource::Group.new("aj")
@current_resource = Chef::Resource::Group.new("aj")
@provider = Chef::Provider::Group::Dscl.new(@new_resource, @run_context)
@provider.current_resource = @current_resource
@status = double(stdout: "\n", stderr: "", exitstatus: 0)
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
end
it "should run shell_out with the supplied array of arguments appended to the dscl command" do
- expect(@provider).to receive(:shell_out).with("dscl", ".", "-cmd", "/Path", "arg1", "arg2")
+ expect(@provider).to receive(:shell_out_compacted).with("dscl", ".", "-cmd", "/Path", "arg1", "arg2")
@provider.dscl("cmd", "/Path", "arg1", "arg2")
end
@@ -45,8 +48,7 @@ describe Chef::Provider::Group::Dscl do
describe "safe_dscl" do
before do
- @node = Chef::Node.new
- @provider = Chef::Provider::Group::Dscl.new(@node, @new_resource)
+ @provider = Chef::Provider::Group::Dscl.new(@new_resource, @run_context)
allow(@provider).to receive(:dscl).and_return(["cmd", @status, "stdout", "stderr"])
end
@@ -93,8 +95,7 @@ describe Chef::Provider::Group::Dscl do
describe "get_free_gid" do
before do
- @node = Chef::Node.new
- @provider = Chef::Provider::Group::Dscl.new(@node, @new_resource)
+ @provider = Chef::Provider::Group::Dscl.new(@new_resource, @run_context)
allow(@provider).to receive(:safe_dscl).and_return("\naj 200\njt 201\n")
end
@@ -115,13 +116,16 @@ describe Chef::Provider::Group::Dscl do
describe "gid_used?" do
before do
- @node = Chef::Node.new
- @provider = Chef::Provider::Group::Dscl.new(@node, @new_resource)
- allow(@provider).to receive(:safe_dscl).and_return("\naj 500\n")
+ allow(@provider).to receive(:safe_dscl).and_return(<<-EOS
+ someprogram somethingElse:gid = (
+ 500
+ )
+ EOS
+ )
end
- it "should run safe_dscl with list /Groups gid" do
- expect(@provider).to receive(:safe_dscl).with(*"list /Groups gid".split(" "))
+ it "should run safe_dscl with search /Groups gid" do
+ expect(@provider).to receive(:safe_dscl).with(*"search /Groups PrimaryGroupID 500".split(" "))
@provider.gid_used?(500)
end
@@ -130,7 +134,11 @@ describe Chef::Provider::Group::Dscl do
end
it "should return false for an unused gid number" do
- expect(@provider.gid_used?(501)).to be_falsey
+ expect(@provider.gid_used?(0)).to be_falsey
+ expect(@provider.gid_used?(50)).to be_falsey
+ expect(@provider.gid_used?(5000)).to be_falsey
+ expect(@provider.gid_used?(1500)).to be_falsey
+ expect(@provider.gid_used?(18)).to be_falsey
end
it "should return false if not given any valid gid number" do
@@ -171,7 +179,7 @@ describe Chef::Provider::Group::Dscl do
describe "with a valid gid number which is not already in use" do
it "should run safe_dscl with create /Groups/group PrimaryGroupID gid" do
allow(@provider).to receive(:get_free_gid).and_return(50)
- expect(@provider).to receive(:safe_dscl).with(*"list /Groups gid".split(" "))
+ expect(@provider).to receive(:safe_dscl).with(*"search /Groups PrimaryGroupID 50".split(" ")).and_return("")
expect(@provider).to receive(:safe_dscl).with("create", "/Groups/aj", "PrimaryGroupID", 50).and_return(true)
@provider.set_gid
end
@@ -188,7 +196,7 @@ describe Chef::Provider::Group::Dscl do
end
it "should log an appropriate message" do
- expect(Chef::Log).to receive(:debug).with("group[aj] removing group members all your base")
+ expect(logger).to receive(:trace).with("group[aj] removing group members all your base")
@provider.set_members
end
@@ -206,7 +214,7 @@ describe Chef::Provider::Group::Dscl do
end
it "should log an appropriate debug message" do
- expect(Chef::Log).to receive(:debug).with("group[aj] setting group members all, your, base")
+ expect(logger).to receive(:trace).with("group[aj] setting group members all, your, base")
@provider.set_members
end
@@ -301,19 +309,19 @@ describe "Test DSCL loading" do
@new_resource = Chef::Resource::Group.new("group name aj")
@new_resource.group_name("aj")
@provider = Chef::Provider::Group::Dscl.new(@new_resource, @run_context)
- @output = <<-EOF
-AppleMetaNodeLocation: /Local/Default
-Comment:
- Test Group
-GeneratedUID: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA
-NestedGroups: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAB
-Password: *
-PrimaryGroupID: 999
-RealName:
- TestGroup
-RecordName: com.apple.aj
-RecordType: dsRecTypeStandard:Groups
-GroupMembership: waka bar
+ @output = <<~EOF
+ AppleMetaNodeLocation: /Local/Default
+ Comment:
+ Test Group
+ GeneratedUID: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA
+ NestedGroups: AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAB
+ Password: *
+ PrimaryGroupID: 999
+ RealName:
+ TestGroup
+ RecordName: com.apple.aj
+ RecordType: dsRecTypeStandard:Groups
+ GroupMembership: waka bar
EOF
allow(@provider).to receive(:safe_dscl).with(*"read /Groups/aj".split(" ")).and_return(@output)
@current_resource = @provider.load_current_resource
diff --git a/spec/unit/provider/group/gpasswd_spec.rb b/spec/unit/provider/group/gpasswd_spec.rb
index add87bf008..506c7b642a 100644
--- a/spec/unit/provider/group/gpasswd_spec.rb
+++ b/spec/unit/provider/group/gpasswd_spec.rb
@@ -19,10 +19,13 @@
require "spec_helper"
describe Chef::Provider::Group::Gpasswd, "modify_group_members" do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
before do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@new_resource = Chef::Resource::Group.new("wheel")
@new_resource.members %w{lobster rage fist}
@new_resource.append false
@@ -65,8 +68,8 @@ describe Chef::Provider::Group::Gpasswd, "modify_group_members" do
end
it "logs a message and sets group's members to 'none'" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] setting group members to: none")
- expect(@provider).to receive(:shell_out!).with("gpasswd", "-M", "", "wheel")
+ expect(logger).to receive(:trace).with("group[wheel] setting group members to: none")
+ expect(@provider).to receive(:shell_out_compacted!).with("gpasswd", "-M", "", "wheel")
@provider.modify_group_members
end
end
@@ -78,20 +81,20 @@ describe Chef::Provider::Group::Gpasswd, "modify_group_members" do
end
it "does not modify group membership" do
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.modify_group_members
end
end
describe "when the resource specifies group members" do
it "should log an appropriate debug message" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] setting group members to: lobster, rage, fist")
- allow(@provider).to receive(:shell_out!)
+ expect(logger).to receive(:trace).with("group[wheel] setting group members to: lobster, rage, fist")
+ allow(@provider).to receive(:shell_out_compacted!)
@provider.modify_group_members
end
it "should run gpasswd with the members joined by ',' followed by the target group" do
- expect(@provider).to receive(:shell_out!).with("gpasswd", "-M", "lobster,rage,fist", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("gpasswd", "-M", "lobster,rage,fist", "wheel")
@provider.modify_group_members
end
@@ -104,9 +107,9 @@ describe Chef::Provider::Group::Gpasswd, "modify_group_members" do
it "should run gpasswd individually for each user when the append option is set" do
@new_resource.append(true)
- expect(@provider).to receive(:shell_out!).with("gpasswd", "-a", "lobster", "wheel")
- expect(@provider).to receive(:shell_out!).with("gpasswd", "-a", "rage", "wheel")
- expect(@provider).to receive(:shell_out!).with("gpasswd", "-a", "fist", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("gpasswd", "-a", "lobster", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("gpasswd", "-a", "rage", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("gpasswd", "-a", "fist", "wheel")
@provider.modify_group_members
end
end
diff --git a/spec/unit/provider/group/groupadd_spec.rb b/spec/unit/provider/group/groupadd_spec.rb
index ded1bc76f1..1aae4fc7f1 100644
--- a/spec/unit/provider/group/groupadd_spec.rb
+++ b/spec/unit/provider/group/groupadd_spec.rb
@@ -108,14 +108,14 @@ describe Chef::Provider::Group::Groupadd do
describe "#create_group" do
before do
- allow(provider).to receive(:shell_out!).and_return(true)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
allow(provider).to receive(:set_options).and_return("monkey")
allow(provider).to receive(:groupadd_options).and_return([])
allow(provider).to receive(:modify_group_members).and_return(true)
end
it "should run groupadd with the return of set_options" do
- expect(provider).to receive(:shell_out!).with("groupadd", "monkey").and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with("groupadd", "monkey").and_return(true)
provider.create_group
end
@@ -127,13 +127,13 @@ describe Chef::Provider::Group::Groupadd do
describe "#manage_group" do
before do
- allow(provider).to receive(:shell_out!).and_return(true)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
allow(provider).to receive(:set_options).and_return("monkey")
end
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(:shell_out!).with("groupmod", "monkey").and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with("groupmod", "monkey").and_return(true)
provider.manage_group
end
@@ -145,12 +145,12 @@ describe Chef::Provider::Group::Groupadd do
describe "#remove_group" do
before do
- allow(provider).to receive(:shell_out!).and_return(true)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
allow(provider).to receive(:set_options).and_return("monkey")
end
it "should run groupdel with the new resources group name" do
- expect(provider).to receive(:shell_out!).with("groupdel", "aj").and_return(true)
+ expect(provider).to receive(:shell_out_compacted!).with("groupdel", "aj").and_return(true)
provider.remove_group
end
end
@@ -163,7 +163,7 @@ describe Chef::Provider::Group::Groupadd do
describe "#load_current_resource" do
before do
- allow(provider).to receive(:shell_out!).and_return(true)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
allow(provider).to receive(:set_options).and_return("monkey")
end
diff --git a/spec/unit/provider/group/groupmod_spec.rb b/spec/unit/provider/group/groupmod_spec.rb
index 6629b718d0..60965f2d47 100644
--- a/spec/unit/provider/group/groupmod_spec.rb
+++ b/spec/unit/provider/group/groupmod_spec.rb
@@ -19,10 +19,13 @@
require "spec_helper"
describe Chef::Provider::Group::Groupmod do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
before do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@new_resource = Chef::Resource::Group.new("wheel")
@new_resource.gid 123
@new_resource.members %w{lobster rage fist}
@@ -61,10 +64,10 @@ describe Chef::Provider::Group::Groupmod do
end
it "logs a message and sets group's members to 'none', then removes existing group members" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] setting group members to: none")
- expect(@provider).to receive(:shell_out!).with("group", "mod", "-n", "wheel_bak", "wheel")
- expect(@provider).to receive(:shell_out!).with("group", "add", "-g", "123", "-o", "wheel")
- expect(@provider).to receive(:shell_out!).with("group", "del", "wheel_bak")
+ expect(logger).to receive(:trace).with("group[wheel] setting group members to: none")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "mod", "-n", "wheel_bak", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "add", "-g", "123", "-o", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "del", "wheel_bak")
@provider.manage_group
end
end
@@ -76,8 +79,8 @@ describe Chef::Provider::Group::Groupmod do
end
it "logs a message and does not modify group membership" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] not changing group members, the group has no members to add")
- expect(@provider).not_to receive(:shell_out!)
+ expect(logger).to receive(:trace).with("group[wheel] not changing group members, the group has no members to add")
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.manage_group
end
end
@@ -89,11 +92,11 @@ describe Chef::Provider::Group::Groupmod do
end
it "updates group membership correctly" do
- allow(Chef::Log).to receive(:debug)
- expect(@provider).to receive(:shell_out!).with("group", "mod", "-n", "wheel_bak", "wheel")
- expect(@provider).to receive(:shell_out!).with("user", "mod", "-G", "wheel", "lobster")
- expect(@provider).to receive(:shell_out!).with("group", "add", "-g", "123", "-o", "wheel")
- expect(@provider).to receive(:shell_out!).with("group", "del", "wheel_bak")
+ allow(logger).to receive(:trace)
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "mod", "-n", "wheel_bak", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("user", "mod", "-G", "wheel", "lobster")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "add", "-g", "123", "-o", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "del", "wheel_bak")
@provider.manage_group
end
end
@@ -108,10 +111,10 @@ describe Chef::Provider::Group::Groupmod do
end
it "should run a group add command and some user mod commands" do
- expect(@provider).to receive(:shell_out!).with("group", "add", "-g", "123", "wheel")
- expect(@provider).to receive(:shell_out!).with("user", "mod", "-G", "wheel", "lobster")
- expect(@provider).to receive(:shell_out!).with("user", "mod", "-G", "wheel", "rage")
- expect(@provider).to receive(:shell_out!).with("user", "mod", "-G", "wheel", "fist")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "add", "-g", "123", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("user", "mod", "-G", "wheel", "lobster")
+ expect(@provider).to receive(:shell_out_compacted!).with("user", "mod", "-G", "wheel", "rage")
+ expect(@provider).to receive(:shell_out_compacted!).with("user", "mod", "-G", "wheel", "fist")
@provider.create_group
end
end
@@ -125,7 +128,7 @@ describe Chef::Provider::Group::Groupmod do
end
it "should run a group del command" do
- expect(@provider).to receive(:shell_out!).with("group", "del", "wheel")
+ expect(@provider).to receive(:shell_out_compacted!).with("group", "del", "wheel")
@provider.remove_group
end
end
diff --git a/spec/unit/provider/group/pw_spec.rb b/spec/unit/provider/group/pw_spec.rb
index ee9ceda8c2..fc42a64566 100644
--- a/spec/unit/provider/group/pw_spec.rb
+++ b/spec/unit/provider/group/pw_spec.rb
@@ -19,10 +19,13 @@
require "spec_helper"
describe Chef::Provider::Group::Pw do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
before do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@new_resource = Chef::Resource::Group.new("wheel")
@new_resource.gid 50
@@ -49,7 +52,7 @@ describe Chef::Provider::Group::Pw do
describe "when creating a group" do
it "should run pw groupadd with the return of set_options and set_members_option" do
@new_resource.gid(23)
- expect(@provider).to receive(:shell_out!).with("pw", "groupadd", "wheel", "-g", "23", "-M", "root,aj").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pw", "groupadd", "wheel", "-g", "23", "-M", "root,aj").and_return(true)
@provider.create_group
end
end
@@ -59,8 +62,8 @@ describe Chef::Provider::Group::Pw do
it "should run pw groupmod with the return of set_options" do
@new_resource.gid(42)
@new_resource.members(["someone"])
- expect(@provider).to receive(:shell_out!).with("pw", "groupmod", "wheel", "-g", "42", "-m", "someone").and_return(true)
- expect(@provider).to receive(:shell_out!).with("pw", "groupmod", "wheel", "-g", "42", "-d", "root,aj").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pw", "groupmod", "wheel", "-g", "42", "-m", "someone").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pw", "groupmod", "wheel", "-g", "42", "-d", "root,aj").and_return(true)
@provider.manage_group
end
@@ -68,7 +71,7 @@ describe Chef::Provider::Group::Pw do
describe "when removing the group" do
it "should run pw groupdel with the new resources group name" do
- expect(@provider).to receive(:shell_out!).with("pw", "groupdel", "wheel").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pw", "groupdel", "wheel").and_return(true)
@provider.remove_group
end
end
@@ -93,7 +96,7 @@ describe Chef::Provider::Group::Pw do
end
it "should log an appropriate message" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] removing group members: all,your,base")
+ expect(logger).to receive(:trace).with("group[wheel] removing group members: all,your,base")
@provider.set_members_options
end
@@ -109,7 +112,7 @@ describe Chef::Provider::Group::Pw do
end
it "should log an appropriate debug message" do
- expect(Chef::Log).to receive(:debug).with("group[wheel] adding group members: all,your,base")
+ expect(logger).to receive(:trace).with("group[wheel] adding group members: all,your,base")
@provider.set_members_options
end
diff --git a/spec/unit/provider/group/suse_spec.rb b/spec/unit/provider/group/suse_spec.rb
index e61d865b6d..29d8f4c58c 100644
--- a/spec/unit/provider/group/suse_spec.rb
+++ b/spec/unit/provider/group/suse_spec.rb
@@ -76,14 +76,14 @@ describe Chef::Provider::Group::Suse do
describe "#add_member" do
it "should call out to groupmod to add user" do
- expect(provider).to receive(:shell_out!).with("groupmod", "-A", "new_user", "new_group")
+ expect(provider).to receive(:shell_out_compacted!).with("groupmod", "-A", "new_user", "new_group")
provider.add_member("new_user")
end
end
describe "#remove_member" do
it "should call out to groupmod to remove user" do
- expect(provider).to receive(:shell_out!).with("groupmod", "-R", "new_user", "new_group")
+ expect(provider).to receive(:shell_out_compacted!).with("groupmod", "-R", "new_user", "new_group")
provider.remove_member("new_user")
end
end
diff --git a/spec/unit/provider/group/usermod_spec.rb b/spec/unit/provider/group/usermod_spec.rb
index da2c20b7da..e34949f839 100644
--- a/spec/unit/provider/group/usermod_spec.rb
+++ b/spec/unit/provider/group/usermod_spec.rb
@@ -39,7 +39,7 @@ describe Chef::Provider::Group::Usermod do
end
it "should log an appropriate message" do
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.modify_group_members
end
end
@@ -85,9 +85,9 @@ describe Chef::Provider::Group::Usermod do
@provider.current_resource = current_resource
@node.automatic_attrs[:platform] = platform
@new_resource.append(true)
- expect(@provider).to receive(:shell_out!).with("usermod", *flags, "wheel", "all")
- expect(@provider).to receive(:shell_out!).with("usermod", *flags, "wheel", "your")
- expect(@provider).to receive(:shell_out!).with("usermod", *flags, "wheel", "base")
+ expect(@provider).to receive(:shell_out_compacted!).with("usermod", *flags, "wheel", "all")
+ expect(@provider).to receive(:shell_out_compacted!).with("usermod", *flags, "wheel", "your")
+ expect(@provider).to receive(:shell_out_compacted!).with("usermod", *flags, "wheel", "base")
@provider.modify_group_members
end
end
diff --git a/spec/unit/provider/group_spec.rb b/spec/unit/provider/group_spec.rb
index c3e0d4b345..437b8c45ea 100644
--- a/spec/unit/provider/group_spec.rb
+++ b/spec/unit/provider/group_spec.rb
@@ -37,9 +37,9 @@ describe Chef::Provider::User do
@provider.current_resource = @current_resource
@pw_group = double("Struct::Group",
- :name => "wheel",
- :gid => 20,
- :mem => %w{root aj}
+ name: "wheel",
+ gid: 20,
+ mem: %w{root aj}
)
allow(Etc).to receive(:getgrnam).with("wheel").and_return(@pw_group)
end
diff --git a/spec/unit/provider/ifconfig/aix_spec.rb b/spec/unit/provider/ifconfig/aix_spec.rb
index 7f316c952b..654b08b2c9 100644
--- a/spec/unit/provider/ifconfig/aix_spec.rb
+++ b/spec/unit/provider/ifconfig/aix_spec.rb
@@ -22,16 +22,16 @@ require "chef/exceptions"
describe Chef::Provider::Ifconfig::Aix do
before(:all) do
- @ifconfig_output = <<-IFCONFIG
-en1: flags=1e080863,480<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,CHECKSUM_OFFLOAD(ACTIVE),CHAIN>
- inet 10.153.11.59 netmask 0xffff0000 broadcast 10.153.255.255
- tcp_sendspace 262144 tcp_recvspace 262144 rfc1323 1
-en0: flags=1e080863,480<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,CHECKSUM_OFFLOAD(ACTIVE),CHAIN> metric 1
- inet 172.29.174.58 netmask 0xffffc000 broadcast 172.29.191.255
- tcp_sendspace 262144 tcp_recvspace 262144 rfc1323 1
-lo0: flags=e08084b,c0<UP,BROADCAST,LOOPBACK,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,LARGESEND,CHAIN>
- inet 127.0.0.1 netmask 0xff000000 broadcast 127.255.255.255
- inet6 ::1%1/0
+ @ifconfig_output = <<~IFCONFIG
+ en1: flags=1e080863,480<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,CHECKSUM_OFFLOAD(ACTIVE),CHAIN>
+ inet 10.153.11.59 netmask 0xffff0000 broadcast 10.153.255.255
+ tcp_sendspace 262144 tcp_recvspace 262144 rfc1323 1
+ en0: flags=1e080863,480<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,CHECKSUM_OFFLOAD(ACTIVE),CHAIN> metric 1
+ inet 172.29.174.58 netmask 0xffffc000 broadcast 172.29.191.255
+ tcp_sendspace 262144 tcp_recvspace 262144 rfc1323 1
+ lo0: flags=e08084b,c0<UP,BROADCAST,LOOPBACK,RUNNING,SIMPLEX,MULTICAST,GROUPRT,64BIT,LARGESEND,CHAIN>
+ inet 127.0.0.1 netmask 0xff000000 broadcast 127.255.255.255
+ inet6 ::1%1/0
IFCONFIG
end
@@ -49,7 +49,7 @@ IFCONFIG
describe "#load_current_resource" do
before do
@status = double(stdout: @ifconfig_output, exitstatus: 0)
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@new_resource.device "en0"
end
@@ -72,7 +72,7 @@ IFCONFIG
@provider.instance_variable_set("@current_resource", Chef::Resource::Ifconfig.new("10.0.0.1", @run_context))
end
command = "chdev -l #{@new_resource.device} -a netaddr=#{@new_resource.name}"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:add)
expect(@new_resource).to be_updated
@@ -98,7 +98,7 @@ IFCONFIG
@provider.instance_variable_set("@current_resource", Chef::Resource::Ifconfig.new("10.0.0.1", @run_context))
end
command = "ifconfig #{@new_resource.device} #{@new_resource.name}"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:enable)
expect(@new_resource).to be_updated
@@ -114,7 +114,7 @@ IFCONFIG
@provider.instance_variable_set("@current_resource", Chef::Resource::Ifconfig.new("10.0.0.1", @run_context))
end
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.run_action(:disable)
expect(@new_resource).not_to be_updated
@@ -133,7 +133,7 @@ IFCONFIG
it "should disable an interface if it exists" do
command = "ifconfig #{@new_resource.device} down"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:disable)
expect(@new_resource).to be_updated
@@ -151,7 +151,7 @@ IFCONFIG
@provider.instance_variable_set("@current_resource", Chef::Resource::Ifconfig.new("10.0.0.1", @run_context))
end
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.run_action(:delete)
expect(@new_resource).not_to be_updated
@@ -170,7 +170,7 @@ IFCONFIG
it "should delete an interface if it exists" do
command = "chdev -l #{@new_resource.device} -a state=down"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:delete)
expect(@new_resource).to be_updated
diff --git a/spec/unit/provider/ifconfig/debian_spec.rb b/spec/unit/provider/ifconfig/debian_spec.rb
index 9a90dc1e0a..93b0008e8b 100644
--- a/spec/unit/provider/ifconfig/debian_spec.rb
+++ b/spec/unit/provider/ifconfig/debian_spec.rb
@@ -119,10 +119,10 @@ describe Chef::Provider::Ifconfig::Debian do
context "when the /etc/network/interfaces file has the source line" do
let(:expected_string) do
- <<-EOF
-a line
-source #{tempdir_path}/*
-another line
+ <<~EOF
+ a line
+ source #{tempdir_path}/*
+ another line
EOF
end
@@ -142,10 +142,10 @@ EOF
context "when the /etc/network/interfaces file does not have the source line" do
let(:expected_string) do
- <<-EOF
-a line
-another line
-source #{tempdir_path}/*
+ <<~EOF
+ a line
+ another line
+ source #{tempdir_path}/*
EOF
end
@@ -246,10 +246,10 @@ EOF
context "when the /etc/network/interfaces file has the source line" do
let(:expected_string) do
- <<-EOF
-a line
-source #{tempdir_path}/*
-another line
+ <<~EOF
+ a line
+ source #{tempdir_path}/*
+ another line
EOF
end
@@ -267,10 +267,10 @@ another line
context "when the /etc/network/interfaces file does not have the source line" do
let(:expected_string) do
- <<-EOF
-a line
-another line
-source #{tempdir_path}/*
+ <<~EOF
+ a line
+ another line
+ source #{tempdir_path}/*
EOF
end
diff --git a/spec/unit/provider/ifconfig_spec.rb b/spec/unit/provider/ifconfig_spec.rb
index da27d647ee..8c63a3e46e 100644
--- a/spec/unit/provider/ifconfig_spec.rb
+++ b/spec/unit/provider/ifconfig_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Prajakta Purohit (prajakta@chef.io)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -38,12 +38,19 @@ 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
+ let(:net_tools_version) { StringIO.new <<~EOS }
+ net-tools 1.60
+ ifconfig 1.42 (2001-04-13)
+EOS
+
before do
- @status = double(stdout: "", exitstatus: 1)
- allow(@provider).to receive(:shell_out).and_return(@status)
+ ifconfig = double(stdout: "", exitstatus: 1)
+ allow(@provider).to receive(:shell_out_compacted).and_return(ifconfig)
+ ifconfig_version = double(stdout: "", stderr: net_tools_version, exitstatus: 4)
+ allow(@provider).to receive(:shell_out_compacted).with("ifconfig", "--version").and_return(ifconfig_version)
@provider.load_current_resource
end
it "should track state of ifconfig failure" do
@@ -60,7 +67,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@current_resource.inet_addr nil
command = "ifconfig eth0 10.0.0.1 netmask 255.255.254.0 metric 1 mtu 1500"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
expect(@provider).to receive(:generate_config)
@provider.run_action(:add)
@@ -71,7 +78,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@new_resource.target "172.16.32.2"
command = "ifconfig eth0 172.16.32.2 netmask 255.255.254.0 metric 1 mtu 1500"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:add)
expect(@new_resource).to be_updated
@@ -79,7 +86,7 @@ describe Chef::Provider::Ifconfig do
it "should not add an interface if it already exists" do
allow(@provider).to receive(:load_current_resource)
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@current_resource.inet_addr "10.0.0.1"
expect(@provider).to receive(:generate_config)
@@ -98,7 +105,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@current_resource.inet_addr nil
command = "ifconfig eth0 10.0.0.1 netmask 255.255.254.0 metric 1 mtu 1500"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
expect(@provider).not_to receive(:generate_config)
@provider.run_action(:enable)
@@ -109,7 +116,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@new_resource.target "172.16.32.2"
command = "ifconfig eth0 172.16.32.2 netmask 255.255.254.0 metric 1 mtu 1500"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
@provider.run_action(:enable)
expect(@new_resource).to be_updated
@@ -132,7 +139,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@current_resource.device "eth0"
command = "ifconfig #{@new_resource.device} down"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
expect(@provider).to receive(:delete_config)
@provider.run_action(:delete)
@@ -141,7 +148,7 @@ describe Chef::Provider::Ifconfig do
it "should not delete interface if it does not exist" do
allow(@provider).to receive(:load_current_resource)
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
expect(@provider).to receive(:delete_config)
@provider.run_action(:delete)
@@ -155,7 +162,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@current_resource.device "eth0"
command = "ifconfig #{@new_resource.device} down"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
expect(@provider).not_to receive(:delete_config)
@provider.run_action(:disable)
@@ -164,7 +171,7 @@ describe Chef::Provider::Ifconfig do
it "should not delete interface if it does not exist" do
allow(@provider).to receive(:load_current_resource)
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
expect(@provider).not_to receive(:delete_config)
@provider.run_action(:disable)
@@ -178,7 +185,7 @@ describe Chef::Provider::Ifconfig do
allow(@provider).to receive(:load_current_resource)
@current_resource.device "eth0"
command = "ifconfig #{@new_resource.device} down"
- expect(@provider).to receive(:shell_out!).with(*command.split(" "))
+ expect(@provider).to receive(:shell_out_compacted!).with(*command.split(" "))
expect(@provider).to receive(:delete_config)
@provider.run_action(:delete)
@@ -189,7 +196,7 @@ describe Chef::Provider::Ifconfig do
# This is so that our fake values do not get overwritten
allow(@provider).to receive(:load_current_resource)
# This is so that nothing actually runs
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
expect(@provider).to receive(:delete_config)
@provider.run_action(:delete)
diff --git a/spec/unit/provider/launchd_spec.rb b/spec/unit/provider/launchd_spec.rb
index 693801f99b..3031ea36c3 100644
--- a/spec/unit/provider/launchd_spec.rb
+++ b/spec/unit/provider/launchd_spec.rb
@@ -29,55 +29,55 @@ describe Chef::Provider::Launchd do
let(:label) { "call.mom.weekly" }
let(:new_resource) { Chef::Resource::Launchd.new(label) }
let!(:current_resource) { Chef::Resource::Launchd.new(label) }
- let(:test_plist) { String.new <<-XML }
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-\t<key>Label</key>
-\t<string>call.mom.weekly</string>
-\t<key>Program</key>
-\t<string>/Library/scripts/call_mom.sh</string>
-\t<key>StartCalendarInterval</key>
-\t<dict>
-\t\t<key>Hour</key>
-\t\t<integer>10</integer>
-\t\t<key>Weekday</key>
-\t\t<integer>7</integer>
-\t</dict>
-\t<key>TimeOut</key>
-\t<integer>300</integer>
-</dict>
-</plist>
+ let(:test_plist) { String.new <<~XML }
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ \t<key>Label</key>
+ \t<string>call.mom.weekly</string>
+ \t<key>Program</key>
+ \t<string>/Library/scripts/call_mom.sh</string>
+ \t<key>StartCalendarInterval</key>
+ \t<dict>
+ \t\t<key>Hour</key>
+ \t\t<integer>10</integer>
+ \t\t<key>Weekday</key>
+ \t\t<integer>7</integer>
+ \t</dict>
+ \t<key>TimeOut</key>
+ \t<integer>300</integer>
+ </dict>
+ </plist>
XML
- let(:test_plist_multiple_intervals) { String.new <<-XML }
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-\t<key>Label</key>
-\t<string>call.mom.weekly</string>
-\t<key>Program</key>
-\t<string>/Library/scripts/call_mom.sh</string>
-\t<key>StartCalendarInterval</key>
-\t<array>
-\t\t<dict>
-\t\t\t<key>Hour</key>
-\t\t\t<integer>11</integer>
-\t\t\t<key>Weekday</key>
-\t\t\t<integer>1</integer>
-\t\t</dict>
-\t\t<dict>
-\t\t\t<key>Hour</key>
-\t\t\t<integer>12</integer>
-\t\t\t<key>Weekday</key>
-\t\t\t<integer>2</integer>
-\t\t</dict>
-\t</array>
-\t<key>TimeOut</key>
-\t<integer>300</integer>
-</dict>
-</plist>
+ let(:test_plist_multiple_intervals) { String.new <<~XML }
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ \t<key>Label</key>
+ \t<string>call.mom.weekly</string>
+ \t<key>Program</key>
+ \t<string>/Library/scripts/call_mom.sh</string>
+ \t<key>StartCalendarInterval</key>
+ \t<array>
+ \t\t<dict>
+ \t\t\t<key>Hour</key>
+ \t\t\t<integer>11</integer>
+ \t\t\t<key>Weekday</key>
+ \t\t\t<integer>1</integer>
+ \t\t</dict>
+ \t\t<dict>
+ \t\t\t<key>Hour</key>
+ \t\t\t<integer>12</integer>
+ \t\t\t<key>Weekday</key>
+ \t\t\t<integer>2</integer>
+ \t\t</dict>
+ \t</array>
+ \t<key>TimeOut</key>
+ \t<integer>300</integer>
+ </dict>
+ </plist>
XML
let(:test_hash) do
@@ -112,14 +112,14 @@ XML
describe "agent" do
it "path should be /Library/LaunchAgents/call.mom.weekly.plist" do
new_resource.type "agent"
- expect(provider.gen_path_from_type).
- to eq("/Library/LaunchAgents/call.mom.weekly.plist")
+ expect(provider.gen_path_from_type)
+ .to eq("/Library/LaunchAgents/call.mom.weekly.plist")
end
end
describe "daemon" do
it "path should be /Library/LaunchDaemons/call.mom.weekly.plist" do
- expect(provider.gen_path_from_type).
- to eq("/Library/LaunchDaemons/call.mom.weekly.plist")
+ expect(provider.gen_path_from_type)
+ .to eq("/Library/LaunchDaemons/call.mom.weekly.plist")
end
end
end
diff --git a/spec/unit/provider/link_spec.rb b/spec/unit/provider/link_spec.rb
index 9426cf41dc..027b318c7e 100644
--- a/spec/unit/provider/link_spec.rb
+++ b/spec/unit/provider/link_spec.rb
@@ -22,14 +22,16 @@ require "ostruct"
require "spec_helper"
if Chef::Platform.windows?
- require "chef/win32/file" #probably need this in spec_helper
+ require "chef/win32/file" # probably need this in spec_helper
end
-describe Chef::Resource::Link, :not_supported_on_win2k3 do
+describe Chef::Resource::Link do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
let(:provider) do
node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
run_context = Chef::RunContext.new(node, {}, @events)
+ allow(run_context).to receive(:logger).and_return(logger)
Chef::Provider::Link.new(new_resource, run_context)
end
let(:new_resource) do
@@ -44,7 +46,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
describe "when the target is a symlink" do
before(:each) do
- lstat = double("stats", :ino => 5)
+ lstat = double("stats", ino: 5)
allow(lstat).to receive(:uid).and_return(501)
allow(lstat).to receive(:gid).and_return(501)
allow(lstat).to receive(:mode).and_return(0777)
@@ -144,7 +146,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
describe "when the target is a regular old file" do
before do
- stat = double("stats", :ino => 5)
+ stat = double("stats", ino: 5)
allow(stat).to receive(:uid).and_return(501)
allow(stat).to receive(:gid).and_return(501)
allow(stat).to receive(:mode).and_return(0755)
@@ -176,7 +178,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
describe "and the source exists" do
before do
- stat = double("stats", :ino => 6)
+ stat = double("stats", ino: 6)
allow(stat).to receive(:uid).and_return(502)
allow(stat).to receive(:gid).and_return(502)
allow(stat).to receive(:mode).and_return(0644)
@@ -203,7 +205,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
describe "and is hardlinked to the source" do
before do
- stat = double("stats", :ino => 5)
+ stat = double("stats", ino: 5)
allow(stat).to receive(:uid).and_return(502)
allow(stat).to receive(:gid).and_return(502)
allow(stat).to receive(:mode).and_return(0644)
@@ -252,7 +254,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
describe "action_delete" do
before(:each) do
- stat = double("stats", :ino => 5)
+ stat = double("stats", ino: 5)
allow(stat).to receive(:uid).and_return(501)
allow(stat).to receive(:gid).and_return(501)
allow(stat).to receive(:mode).and_return(0755)
@@ -270,7 +272,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
it "invokes Dir.delete method to delete the link" do
expect(::Dir).to receive(:delete).with(provider.new_resource.target_file)
- expect(Chef::Log).to receive(:info).with("#{provider.new_resource} deleted")
+ expect(logger).to receive(:info).with("#{provider.new_resource} deleted")
provider.run_action(:delete)
end
end
@@ -283,7 +285,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
it "invokes File.delete method to delete the link" do
expect(::File).to receive(:delete).with(provider.new_resource.target_file)
- expect(Chef::Log).to receive(:info).with("#{provider.new_resource} deleted")
+ expect(logger).to receive(:info).with("#{provider.new_resource} deleted")
provider.run_action(:delete)
end
end
@@ -296,7 +298,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
it "invokes File.delete method to delete the link" do
expect(::File).to receive(:delete).with(provider.new_resource.target_file)
- expect(Chef::Log).to receive(:info).with("#{provider.new_resource} deleted")
+ expect(logger).to receive(:info).with("#{provider.new_resource} deleted")
provider.run_action(:delete)
end
end
@@ -319,7 +321,7 @@ describe Chef::Resource::Link, :not_supported_on_win2k3 do
end
before(:each) do
- stat = double("stats", :ino => 5)
+ stat = double("stats", ino: 5)
allow(stat).to receive(:uid).and_return(502)
allow(stat).to receive(:gid).and_return(502)
allow(stat).to receive(:mode).and_return(0644)
diff --git a/spec/unit/provider/log_spec.rb b/spec/unit/provider/log_spec.rb
index ce7b1af55a..deb2024640 100644
--- a/spec/unit/provider/log_spec.rb
+++ b/spec/unit/provider/log_spec.rb
@@ -32,44 +32,49 @@ describe Chef::Provider::Log::ChefLog do
let(:provider) { Chef::Provider::Log::ChefLog.new(new_resource, run_context) }
- it "should write the string to the Chef::Log object at default level (info)" do
- expect(Chef::Log).to receive(:info).with(log_str).and_return(true)
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ before do
+ allow(run_context).to receive(:logger).and_return(logger)
+ end
+
+ it "should write the string to the logger object at default level (info)" do
+ expect(logger).to receive(:info).with(log_str).and_return(true)
provider.run_action(:write)
end
- it "should write the string to the Chef::Log object at debug level" do
+ it "should write the string to the logger object at debug level" do
new_resource.level :debug
- expect(Chef::Log).to receive(:debug).with(log_str).and_return(true)
+ expect(logger).to receive(:debug).with(log_str).and_return(true)
provider.run_action(:write)
end
- it "should write the string to the Chef::Log object at info level" do
+ it "should write the string to the logger object at info level" do
new_resource.level :info
- expect(Chef::Log).to receive(:info).with(log_str).and_return(true)
+ expect(logger).to receive(:info).with(log_str).and_return(true)
provider.run_action(:write)
end
- it "should write the string to the Chef::Log object at warn level" do
+ it "should write the string to the logger object at warn level" do
new_resource.level :warn
- expect(Chef::Log).to receive(:warn).with(log_str).and_return(true)
+ expect(logger).to receive(:warn).with(log_str).and_return(true)
provider.run_action(:write)
end
- it "should write the string to the Chef::Log object at error level" do
+ it "should write the string to the logger object at error level" do
new_resource.level :error
- expect(Chef::Log).to receive(:error).with(log_str).and_return(true)
+ expect(logger).to receive(:error).with(log_str).and_return(true)
provider.run_action(:write)
end
- it "should write the string to the Chef::Log object at fatal level" do
+ it "should write the string to the logger object at fatal level" do
new_resource.level :fatal
- expect(Chef::Log).to receive(:fatal).with(log_str).and_return(true)
+ expect(logger).to receive(:fatal).with(log_str).and_return(true)
provider.run_action(:write)
end
it "should print the string in why-run mode" do
Chef::Config[:why_run] = true
- expect(Chef::Log).to receive(:info).with(log_str).and_return(true)
+ expect(logger).to receive(:info).with(log_str).and_return(true)
provider.run_action(:write)
end
diff --git a/spec/unit/provider/mdadm_spec.rb b/spec/unit/provider/mdadm_spec.rb
index 8ef884e131..d79c1b35db 100644
--- a/spec/unit/provider/mdadm_spec.rb
+++ b/spec/unit/provider/mdadm_spec.rb
@@ -32,20 +32,20 @@ describe Chef::Provider::Mdadm do
describe "when determining the current metadevice status" do
it "should set the current resources mount point to the new resources mount point" do
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:status => 0))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(status: 0))
@provider.load_current_resource
expect(@provider.current_resource.name).to eq("/dev/md1")
expect(@provider.current_resource.raid_device).to eq("/dev/md1")
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_compacted!).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_compacted!).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
diff --git a/spec/unit/provider/mount/aix_spec.rb b/spec/unit/provider/mount/aix_spec.rb
index 615f3c3304..b472e60710 100644
--- a/spec/unit/provider/mount/aix_spec.rb
+++ b/spec/unit/provider/mount/aix_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Kaustubh Deorukhkar (<kaustubh@clogeny.com>)
-# Copyright:: Copyright 2013-2016, Chef Software Inc.
+# Copyright:: Copyright 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,32 +22,32 @@ require "ostruct"
describe Chef::Provider::Mount::Aix do
before(:all) do
- @mounted_output = <<-MOUNT
- node mounted mounted over vfs date options
--------- --------------- --------------- ------ ------------ ---------------
- /dev/sdz1 /tmp/foo jfs2 Jul 17 13:22 rw,log=/dev/hd8
+ @mounted_output = <<~MOUNT
+ node mounted mounted over vfs date options
+ -------- --------------- --------------- ------ ------------ ---------------
+ /dev/sdz1 /tmp/foo jfs2 Jul 17 13:22 rw,log=/dev/hd8
MOUNT
- @unmounted_output = <<-UNMOUNTED
- node mounted mounted over vfs date options
--------- --------------- --------------- ------ ------------ ---------------
- /dev/sdz2 / jfs2 Jul 17 13:22 rw,log=/dev/hd8
+ @unmounted_output = <<~UNMOUNTED
+ node mounted mounted over vfs date options
+ -------- --------------- --------------- ------ ------------ ---------------
+ /dev/sdz2 / jfs2 Jul 17 13:22 rw,log=/dev/hd8
UNMOUNTED
- @conflict_mounted_output = <<-MOUNT
- node mounted mounted over vfs date options
--------- --------------- --------------- ------ ------------ ---------------
- /dev/sdz3 /tmp/foo jfs2 Jul 17 13:22 rw,log=/dev/hd8
+ @conflict_mounted_output = <<~MOUNT
+ node mounted mounted over vfs date options
+ -------- --------------- --------------- ------ ------------ ---------------
+ /dev/sdz3 /tmp/foo jfs2 Jul 17 13:22 rw,log=/dev/hd8
MOUNT
- @enabled_output = <<-ENABLED
-#MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct
-/tmp/foo:/dev/sdz1:jfs2::bootfs:10485760:rw:yes:no
+ @enabled_output = <<~ENABLED
+ #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct
+ /tmp/foo:/dev/sdz1:jfs2::bootfs:10485760:rw:yes:no
ENABLED
- @test_wrong_output = <<-WRONG
-#MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct
-/tmp/foo::/dev/sdz1:jfs2:bootfs:10485760:rw:yes:no
+ @test_wrong_output = <<~WRONG
+ #MountPoint:Device:Vfs:Nodename:Type:Size:Options:AutoMount:Acct
+ /tmp/foo::/dev/sdz1:jfs2:bootfs:10485760:rw:yes:no
WRONG
end
@@ -61,7 +61,7 @@ WRONG
@new_resource.device_type :device
@new_resource.fstype "jfs2"
- @new_resource.supports :remount => false
+ @new_resource.supports remount: false
@provider = Chef::Provider::Mount::Aix.new(@new_resource, @run_context)
@@ -70,13 +70,13 @@ WRONG
end
def stub_mounted(provider, mounted_output)
- response = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => mounted_output, :stderr => "")
- expect(provider).to receive(:shell_out!).with("mount").and_return(response)
+ response = double("Mixlib::ShellOut command", exitstatus: 0, stdout: mounted_output, stderr: "")
+ expect(provider).to receive(:shell_out_compacted!).with("mount").and_return(response)
end
def stub_enabled(provider, enabled_output)
- response = double("Mixlib::ShellOut command", :exitstatus => 0, :stdout => enabled_output, :stderr => "")
- expect(provider).to receive(:shell_out).with("lsfs -c #{@new_resource.mount_point}").and_return(response)
+ response = double("Mixlib::ShellOut command", exitstatus: 0, stdout: enabled_output, stderr: "")
+ expect(provider).to receive(:shell_out_compacted).with("lsfs", "-c", @new_resource.mount_point).and_return(response)
end
def stub_mounted_enabled(provider, mounted_output, enabled_output)
@@ -145,7 +145,7 @@ WRONG
it "should mount resource if it is not mounted" do
stub_mounted_enabled(@provider, @unmounted_output, "")
- expect(@provider).to receive(:shell_out!).with("mount -v #{@new_resource.fstype} #{@new_resource.device} #{@new_resource.mount_point}")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-v", @new_resource.fstype, @new_resource.device, @new_resource.mount_point)
@provider.run_action(:mount)
end
@@ -163,7 +163,7 @@ WRONG
it "should umount resource if it is already mounted" do
stub_mounted_enabled(@provider, @mounted_output, "")
- expect(@provider).to receive(:shell_out!).with("umount #{@new_resource.mount_point}")
+ expect(@provider).to receive(:shell_out_compacted!).with("umount", @new_resource.mount_point)
@provider.run_action(:umount)
end
@@ -179,20 +179,20 @@ WRONG
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}")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount", @new_resource.device, @new_resource.mount_point)
@provider.run_action(:remount)
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, "")
- expect(@provider).to receive(:shell_out!).with("mount -o remount,nodev,rw #{@new_resource.device} #{@new_resource.mount_point}")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount,nodev,rw", @new_resource.device, @new_resource.mount_point)
@provider.run_action(:remount)
end
@@ -232,22 +232,22 @@ WRONG
it "should disable mount if it is mounted and enabled" do
stub_mounted_enabled(@provider, @mounted_output, @enabled_output)
- allow(::File).to receive(:open).with("/etc/filesystems", "r").and_return(<<-ETCFILESYSTEMS)
-/tmp/foo:
- dev = /dev/sdz1
- vfs = jfs2
- log = /dev/hd8
- mount = true
- check = true
- vol = /opt
- free = false
- quota = no
-
-/tmp/abc:
- dev = /dev/sdz2
- vfs = jfs2
- mount = true
- options = rw
+ allow(::File).to receive(:open).with("/etc/filesystems", "r").and_return(<<~ETCFILESYSTEMS)
+ /tmp/foo:
+ dev = /dev/sdz1
+ vfs = jfs2
+ log = /dev/hd8
+ mount = true
+ check = true
+ vol = /opt
+ free = false
+ quota = no
+
+ /tmp/abc:
+ dev = /dev/sdz2
+ vfs = jfs2
+ mount = true
+ options = rw
ETCFILESYSTEMS
filesystems = StringIO.new
diff --git a/spec/unit/provider/mount/mount_spec.rb b/spec/unit/provider/mount/mount_spec.rb
index 20a4fd88dd..2af3c93fc9 100644
--- a/spec/unit/provider/mount/mount_spec.rb
+++ b/spec/unit/provider/mount/mount_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Joshua Timberman (<joshua@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,7 +30,7 @@ describe Chef::Provider::Mount::Mount do
@new_resource.device_type :device
@new_resource.fstype "ext3"
- @new_resource.supports :remount => false
+ @new_resource.supports remount: false
@provider = Chef::Provider::Mount::Mount.new(@new_resource, @run_context)
@@ -42,7 +42,7 @@ describe Chef::Provider::Mount::Mount do
describe "when discovering the current fs state" do
before do
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => ""))
+ allow(@provider).to receive(:shell_out_compacted!).and_return(OpenStruct.new(stdout: ""))
allow(::File).to receive(:foreach).with("/etc/fstab")
end
@@ -53,13 +53,13 @@ describe Chef::Provider::Mount::Mount do
expect(@provider.current_resource.device).to eq("/dev/sdz1")
end
- it "should accecpt device_type :uuid", :not_supported_on_solaris do
- @status = double(:stdout => "/dev/sdz1\n", :exitstatus => 1)
+ it "should accept device_type :uuid", :not_supported_on_solaris do
+ @status = double(stdout: "/dev/sdz1\n", exitstatus: 1)
@new_resource.device_type :uuid
@new_resource.device "d21afe51-a0fe-4dc6-9152-ac733763ae0a"
- @stdout_findfs = double("STDOUT", :first => "/dev/sdz1")
- expect(@provider).to receive(:shell_out).with("/sbin/findfs UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(@status)
- @provider.load_current_resource()
+ @stdout_findfs = double("STDOUT", first: "/dev/sdz1")
+ expect(@provider).to receive(:shell_out_compacted).with("/sbin/findfs", "UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(@status)
+ @provider.load_current_resource
@provider.mountable?
end
@@ -73,7 +73,7 @@ describe Chef::Provider::Mount::Mount do
it "should ignore trailing slash and set mounted to true for network mount (#{type})" do
@new_resource.device fs_spec
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{fs_spec}/ on /tmp/foo type #{type} (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{fs_spec}/ on /tmp/foo type #{type} (rw)\n"))
@provider.load_current_resource
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -94,10 +94,10 @@ describe Chef::Provider::Mount::Mount do
end
it "should raise an error if the mount device (uuid) does not exist", :not_supported_on_solaris do
- status = double(:stdout => "", :exitstatus => 1)
+ status = double(stdout: "", exitstatus: 1)
@new_resource.device_type :uuid
@new_resource.device "d21afe51-a0fe-4dc6-9152-ac733763ae0a"
- expect(@provider).to receive(:shell_out).with("/sbin/findfs UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("/sbin/findfs", "UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
expect(::File).to receive(:exists?).with("").and_return(false)
expect { @provider.load_current_resource(); @provider.mountable? }.to raise_error(Chef::Exceptions::Mount)
end
@@ -121,13 +121,13 @@ describe Chef::Provider::Mount::Mount do
end
it "should set mounted true if the mount point is found in the mounts list" do
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdz1 on /tmp/foo type ext3 (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdz1 on /tmp/foo type ext3 (rw)\n"))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_truthy
end
it "should set mounted false if another mount point beginning with the same path is found in the mounts list" do
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdz1 on /tmp/foobar type ext3 (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdz1 on /tmp/foobar type ext3 (rw)\n"))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_falsey
end
@@ -136,10 +136,10 @@ describe Chef::Provider::Mount::Mount do
# expand the target path to correct specs on Windows
target = ::File.expand_path("/dev/mapper/target")
- allow(::File).to receive(:symlink?).with("#{@new_resource.device}").and_return(true)
- allow(::File).to receive(:readlink).with("#{@new_resource.device}").and_return(target)
+ allow(::File).to receive(:symlink?).with((@new_resource.device).to_s).and_return(true)
+ allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{target} on /tmp/foo type ext3 (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{target} on /tmp/foo type ext3 (rw)\n"))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -150,10 +150,10 @@ describe Chef::Provider::Mount::Mount do
# expand the target path to correct specs on Windows
absolute_target = ::File.expand_path("/dev/xsdz1")
- allow(::File).to receive(:symlink?).with("#{@new_resource.device}").and_return(true)
- allow(::File).to receive(:readlink).with("#{@new_resource.device}").and_return(target)
+ allow(::File).to receive(:symlink?).with((@new_resource.device).to_s).and_return(true)
+ allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "#{absolute_target} on /tmp/foo type ext3 (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "#{absolute_target} on /tmp/foo type ext3 (rw)\n"))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -162,7 +162,7 @@ describe Chef::Provider::Mount::Mount do
mount = "/dev/sdy1 on #{@new_resource.mount_point} type ext3 (rw)\n"
mount << "#{@new_resource.device} on #{@new_resource.mount_point} type ext3 (rw)\n"
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => mount))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: mount))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_truthy
end
@@ -171,13 +171,13 @@ describe Chef::Provider::Mount::Mount do
mount = "#{@new_resource.device} on #{@new_resource.mount_point} type ext3 (rw)\n"
mount << "/dev/sdy1 on #{@new_resource.mount_point} type ext3 (rw)\n"
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => mount))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: mount))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_falsey
end
it "mounted should be false if the mount point is not found in the mounts list" do
- allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "/dev/sdy1 on /tmp/foo type ext3 (rw)\n"))
+ allow(@provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "/dev/sdy1 on /tmp/foo type ext3 (rw)\n"))
@provider.load_current_resource()
expect(@provider.current_resource.mounted).to be_falsey
end
@@ -205,8 +205,8 @@ describe Chef::Provider::Mount::Mount do
it "should set enabled to true if the symlink target is in fstab" do
target = "/dev/mapper/target"
- allow(::File).to receive(:symlink?).with("#{@new_resource.device}").and_return(true)
- allow(::File).to receive(:readlink).with("#{@new_resource.device}").and_return(target)
+ allow(::File).to receive(:symlink?).with((@new_resource.device).to_s).and_return(true)
+ allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
fstab = "/dev/sdz1 /tmp/foo ext3 defaults 1 2\n"
@@ -219,8 +219,8 @@ describe Chef::Provider::Mount::Mount do
it "should set enabled to true if the symlink target is relative and is in fstab - CHEF-4957" do
target = "xsdz1"
- allow(::File).to receive(:symlink?).with("#{@new_resource.device}").and_return(true)
- allow(::File).to receive(:readlink).with("#{@new_resource.device}").and_return(target)
+ allow(::File).to receive(:symlink?).with((@new_resource.device).to_s).and_return(true)
+ allow(::File).to receive(:readlink).with((@new_resource.device).to_s).and_return(target)
fstab = "/dev/sdz1 /tmp/foo ext3 defaults 1 2\n"
@@ -295,25 +295,25 @@ describe Chef::Provider::Mount::Mount do
describe "mount_fs" do
it "should mount the filesystem if it is not mounted" do
- expect(@provider).to receive(:shell_out!).with("mount -t ext3 -o defaults /dev/sdz1 /tmp/foo")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", "ext3", "-o", "defaults", "/dev/sdz1", "/tmp/foo")
@provider.mount_fs()
end
it "should mount the filesystem with options if options were passed" do
options = "rw,noexec,noauto"
@new_resource.options(%w{rw noexec noauto})
- expect(@provider).to receive(:shell_out!).with("mount -t ext3 -o rw,noexec,noauto /dev/sdz1 /tmp/foo")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", "ext3", "-o", "rw,noexec,noauto", "/dev/sdz1", "/tmp/foo")
@provider.mount_fs()
end
it "should mount the filesystem specified by uuid", :not_supported_on_solaris do
- status = double(:stdout => "/dev/sdz1\n", :exitstatus => 1)
+ status = double(stdout: "/dev/sdz1\n", exitstatus: 1)
@new_resource.device "d21afe51-a0fe-4dc6-9152-ac733763ae0a"
@new_resource.device_type :uuid
- allow(@provider).to receive(:shell_out).with("/sbin/findfs UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
+ allow(@provider).to receive(:shell_out_compacted).with("/sbin/findfs", "UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
@stdout_mock = double("stdout mock")
allow(@stdout_mock).to receive(:each).and_yield("#{@new_resource.device} on #{@new_resource.mount_point}")
- expect(@provider).to receive(:shell_out!).with("mount -t #{@new_resource.fstype} -o defaults -U #{@new_resource.device} #{@new_resource.mount_point}").and_return(@stdout_mock)
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-t", @new_resource.fstype, "-o", "defaults", "-U", @new_resource.device, @new_resource.mount_point).and_return(@stdout_mock)
@provider.mount_fs()
end
@@ -328,7 +328,7 @@ describe Chef::Provider::Mount::Mount do
describe "umount_fs" do
it "should umount the filesystem if it is mounted" do
@current_resource.mounted(true)
- expect(@provider).to receive(:shell_out!).with("umount /tmp/foo")
+ expect(@provider).to receive(:shell_out!).with("umount", "/tmp/foo")
@provider.umount_fs()
end
@@ -341,23 +341,23 @@ 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}")
+ expect(@provider).to receive(:shell_out_compacted!).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)
- expect(@provider).to receive(:shell_out!).with("mount -o remount,rw,noexec,noauto #{@new_resource.mount_point}")
+ expect(@provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount,rw,noexec,noauto", @new_resource.mount_point)
@provider.remount_fs
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)
@@ -374,6 +374,28 @@ describe Chef::Provider::Mount::Mount do
end
end
+ describe "default_mount_options" do
+ it "should return the correct default mount options for Linux" do
+ @provider.node.override[:os] = "linux"
+ expect(@provider.default_mount_options).to eq("defaults")
+ end
+
+ it "should return the correct default mount options for AIX" do
+ @provider.node.override[:os] = "aix"
+ expect(@provider.default_mount_options).to eq("rw")
+ end
+
+ it "should return the correct default mount options for Darwin" do
+ @provider.node.override[:os] = "darwin"
+ expect(@provider.default_mount_options).to eq("rw")
+ end
+
+ it "should return the correct default mount options for FreeBSD" do
+ @provider.node.override[:os] = "freebsd"
+ expect(@provider.default_mount_options).to eq("rw")
+ end
+ end
+
describe "when enabling the fs" do
it "should enable if enabled isn't true" do
@current_resource.enabled(false)
@@ -470,5 +492,35 @@ describe Chef::Provider::Mount::Mount do
@provider.disable_fs
end
end
+
+ # the fstab might contain the mount with the device as a device but the resource has a label.
+ # we should not create two mount lines, but update the existing one
+ # not supported on solaris because it can't cope with a UUID device type
+ context "when the device is described differently", :not_supported_on_solaris do
+ it "should update the existing line" do
+ @current_resource.enabled(true)
+ status = double(stdout: "/dev/sdz1\n", exitstatus: 1)
+ expect(@provider).to receive(:shell_out_compacted).with("/sbin/findfs", "UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a").and_return(status)
+
+ filesystems = [%q{/dev/sdy1 /tmp/foo ext3 defaults 1 2},
+ %q{/dev/sdz1 /tmp/foo ext3 defaults 1 2}].join("\n")
+ fstab = StringIO.new filesystems
+
+ fstab_write = StringIO.new
+
+ allow(::File).to receive(:readlines).with("/etc/fstab").and_return(fstab.readlines)
+ allow(::File).to receive(:open).with("/etc/fstab", "w").and_yield(fstab_write)
+ allow(::File).to receive(:open).with("/etc/fstab", "a").and_yield(fstab_write)
+
+ @new_resource.device_type :uuid
+ @new_resource.device "d21afe51-a0fe-4dc6-9152-ac733763ae0a"
+ @new_resource.dump 1
+
+ @provider.enable_fs
+ expect(fstab_write.string).to match(%r{/dev/sdy1\s+/tmp/foo\s+ext3\s+defaults\s+1\s+2})
+ expect(fstab_write.string).to match(%r{UUID=d21afe51-a0fe-4dc6-9152-ac733763ae0a\s+/tmp/foo\s+ext3\s+defaults\s+1\s+2})
+ expect(fstab_write.string).not_to match(%r{/dev/sdz1\s+/tmp/foo\s+ext3\s+defaults\s+1\s+2})
+ end
+ end
end
end
diff --git a/spec/unit/provider/mount/solaris_spec.rb b/spec/unit/provider/mount/solaris_spec.rb
index 264c8b9b36..4e73bc77b5 100644
--- a/spec/unit/provider/mount/solaris_spec.rb
+++ b/spec/unit/provider/mount/solaris_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Lamont Granquist (<lamont@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software, Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -48,7 +48,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
new_resource.fsck_device fsck_device
new_resource.fstype fstype
new_resource.options options
- new_resource.supports :remount => false
+ new_resource.supports remount: false
new_resource
end
@@ -57,22 +57,22 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
end
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- #device device mount FS fsck mount mount
- #to mount to fsck point type pass at boot options
- #
- fd - /dev/fd fd - no -
- /proc - /proc proc - no -
- # swap
- /dev/dsk/c0t0d0s1 - - swap - no -
- # root
- /dev/dsk/c0t0d0s0 /dev/rdsk/c0t0d0s0 / ufs 1 no -
- # tmpfs
- swap - /tmp tmpfs - yes -
- # nfs
- cartman:/share2 - /cartman nfs - yes rw,soft
- # ufs
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ #device device mount FS fsck mount mount
+ #to mount to fsck point type pass at boot options
+ #
+ fd - /dev/fd fd - no -
+ /proc - /proc proc - no -
+ # swap
+ /dev/dsk/c0t0d0s1 - - swap - no -
+ # root
+ /dev/dsk/c0t0d0s0 /dev/rdsk/c0t0d0s0 / ufs 1 no -
+ # tmpfs
+ swap - /tmp tmpfs - yes -
+ # nfs
+ cartman:/share2 - /cartman nfs - yes rw,soft
+ # ufs
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -84,15 +84,15 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
end
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t0d0s0 on / type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
- /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ /dev/dsk/c0t0d0s0 on / type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
+ /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
before do
stub_const("Chef::Provider::Mount::Solaris::VFSTAB", vfstab_file.path )
- allow(provider).to receive(:shell_out!).with("mount -v").and_return(OpenStruct.new(:stdout => mount_output))
+ allow(provider).to receive(:shell_out_compacted!).with("mount", "-v").and_return(OpenStruct.new(stdout: mount_output))
allow(File).to receive(:symlink?).with(device).and_return(false)
allow(File).to receive(:exist?).and_call_original # Tempfile.open on ruby 1.8.7 calls File.exist?
allow(File).to receive(:exist?).with(device).and_return(true)
@@ -215,22 +215,22 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when loading a normal UFS filesystem with noauto, don't mount at boot" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- #device device mount FS fsck mount mount
- #to mount to fsck point type pass at boot options
- #
- fd - /dev/fd fd - no -
- /proc - /proc proc - no -
- # swap
- /dev/dsk/c0t0d0s1 - - swap - no -
- # root
- /dev/dsk/c0t0d0s0 /dev/rdsk/c0t0d0s0 / ufs 1 no -
- # tmpfs
- swap - /tmp tmpfs - yes -
- # nfs
- cartman:/share2 - /cartman nfs - yes rw,soft
- # ufs
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 no -
+ <<~EOF
+ #device device mount FS fsck mount mount
+ #to mount to fsck point type pass at boot options
+ #
+ fd - /dev/fd fd - no -
+ /proc - /proc proc - no -
+ # swap
+ /dev/dsk/c0t0d0s1 - - swap - no -
+ # root
+ /dev/dsk/c0t0d0s0 /dev/rdsk/c0t0d0s0 / ufs 1 no -
+ # tmpfs
+ swap - /tmp tmpfs - yes -
+ # nfs
+ cartman:/share2 - /cartman nfs - yes rw,soft
+ # ufs
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 no -
EOF
end
@@ -245,13 +245,13 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the device is an smbfs mount" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- //solarsystem/tmp on /mnt type smbfs read/write/setuid/devices/dev=5080000 on Tue Mar 29 11:40:18 2011
+ <<~EOF
+ //solarsystem/tmp on /mnt type smbfs read/write/setuid/devices/dev=5080000 on Tue Mar 29 11:40:18 2011
EOF
end
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- //WORKGROUP;username:password@host/share - /mountpoint smbfs - no fileperms=0777,dirperms=0777
+ <<~EOF
+ //WORKGROUP;username:password@host/share - /mountpoint smbfs - no fileperms=0777,dirperms=0777
EOF
end
@@ -264,14 +264,14 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the device is an NFS mount" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- cartman:/share2 on /cartman type nfs rsize=32768,wsize=32768,NFSv4,dev=4000004 on Tue Mar 29 11:40:18 2011
+ <<~EOF
+ cartman:/share2 on /cartman type nfs rsize=32768,wsize=32768,NFSv4,dev=4000004 on Tue Mar 29 11:40:18 2011
EOF
end
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- cartman:/share2 - /cartman nfs - yes rw,soft
+ <<~EOF
+ cartman:/share2 - /cartman nfs - yes rw,soft
EOF
end
@@ -335,14 +335,14 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
let(:target) { "/dev/mapper/target" }
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- #{target} on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ #{target} on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- #{target} /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ #{target} /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -372,14 +372,14 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
let(:absolute_target) { File.expand_path(target, File.dirname(device)) }
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- #{absolute_target} on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ #{absolute_target} on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- #{absolute_target} /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ #{absolute_target} /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -405,9 +405,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the matching mount point is last in the mounts list" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t0d0s0 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
- /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ /dev/dsk/c0t0d0s0 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
+ /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
it "should set mounted true" do
@@ -418,9 +418,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the matching mount point is not last in the mounts list" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
- /dev/dsk/c0t0d0s0 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ /dev/dsk/c0t2d0s7 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ /dev/dsk/c0t0d0s0 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200000 on Tue Jul 31 22:34:46 2012
EOF
end
it "should set mounted false" do
@@ -431,8 +431,8 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the matching mount point is not in the mounts list (mountpoint wrong)" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s7 on /mnt/foob type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ /dev/dsk/c0t2d0s7 on /mnt/foob type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
it "should set mounted false" do
@@ -443,8 +443,8 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the matching mount point is not in the mounts list (raw device wrong)" do
let(:mount_output) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s72 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
+ <<~EOF
+ /dev/dsk/c0t2d0s72 on /mnt/foo type ufs read/write/setuid/intr/largefiles/xattr/onerror=panic/dev=2200007 on Tue Jul 31 22:34:46 2012
EOF
end
it "should set mounted false" do
@@ -455,9 +455,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mount point is last in fstab" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -469,9 +469,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mount point is not last in fstab and is a substring of another mount" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
- /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo/bar ufs 2 yes -
+ <<~EOF
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo/bar ufs 2 yes -
EOF
end
@@ -483,9 +483,9 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mount point is not last in fstab" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
- /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s72 /mnt/foo ufs 2 yes -
+ <<~EOF
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s72 /mnt/foo ufs 2 yes -
EOF
end
@@ -497,8 +497,8 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mount point is not in fstab, but the mountpoint is a substring of one that is" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foob ufs 2 yes -
+ <<~EOF
+ /dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foob ufs 2 yes -
EOF
end
@@ -510,8 +510,8 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mount point is not in fstab, but the device is a substring of one that is" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ /dev/dsk/c0t2d0s72 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -523,8 +523,8 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "when the mountpoint line is commented out" do
let(:vfstab_file_contents) do
- <<-EOF.gsub /^\s*/, ""
- #/dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
+ <<~EOF
+ #/dev/dsk/c0t2d0s7 /dev/rdsk/c0t2d0s7 /mnt/foo ufs 2 yes -
EOF
end
@@ -538,28 +538,28 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "after the mount's state has been discovered" do
describe "mount_fs" do
it "should mount the filesystem" do
- expect(provider).to receive(:shell_out!).with("mount -F #{fstype} -o defaults #{device} #{mountpoint}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, device, mountpoint)
provider.mount_fs()
end
it "should mount the filesystem with options if options were passed" do
options = "logging,noatime,largefiles,nosuid,rw,quota"
new_resource.options(options.split(/,/))
- expect(provider).to receive(:shell_out!).with("mount -F #{fstype} -o #{options} #{device} #{mountpoint}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, "-o", options, device, mountpoint)
provider.mount_fs()
end
it "should delete the 'noauto' magic option" do
options = "rw,noauto"
new_resource.options(%w{rw noauto})
- expect(provider).to receive(:shell_out!).with("mount -F #{fstype} -o rw #{device} #{mountpoint}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-F", fstype, "-o", "rw", device, mountpoint)
provider.mount_fs()
end
end
describe "umount_fs" do
it "should umount the filesystem if it is mounted" do
- expect(provider).to receive(:shell_out!).with("umount #{mountpoint}")
+ expect(provider).to receive(:shell_out_compacted!).with("umount", mountpoint)
provider.umount_fs()
end
end
@@ -567,7 +567,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "remount_fs without options and do not mount at boot" do
it "should use mount -o remount" do
new_resource.options(%w{noauto})
- expect(provider).to receive(:shell_out!).with("mount -o remount #{new_resource.mount_point}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount", new_resource.mount_point)
provider.remount_fs
end
end
@@ -575,7 +575,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "remount_fs with options and do not mount at boot" do
it "should use mount -o remount,rw" do
new_resource.options(%w{rw noauto})
- expect(provider).to receive(:shell_out!).with("mount -o remount,rw #{new_resource.mount_point}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount,rw", new_resource.mount_point)
provider.remount_fs
end
end
@@ -583,7 +583,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "remount_fs with options and mount at boot" do
it "should use mount -o remount,rw" do
new_resource.options(%w{rw})
- expect(provider).to receive(:shell_out!).with("mount -o remount,rw #{new_resource.mount_point}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount,rw", new_resource.mount_point)
provider.remount_fs
end
end
@@ -591,7 +591,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
describe "remount_fs without options and mount at boot" do
it "should use mount -o remount" do
new_resource.options([])
- expect(provider).to receive(:shell_out!).with("mount -o remount #{new_resource.mount_point}")
+ expect(provider).to receive(:shell_out_compacted!).with("mount", "-o", "remount", new_resource.mount_point)
provider.remount_fs
end
end
@@ -600,7 +600,7 @@ describe Chef::Provider::Mount::Solaris, :unix_only do
context "in the typical case" do
let(:other_mount) { "/dev/dsk/c0t2d0s0 /dev/rdsk/c0t2d0s0 / ufs 2 yes -" }
- let(:this_mount) { "/dev/dsk/c0t2d0s7\t/dev/rdsk/c0t2d0s7\t/mnt/foo\tufs\t2\tyes\tdefaults\n" }
+ let(:this_mount) { "/dev/dsk/c0t2d0s7\t/dev/rdsk/c0t2d0s7\t/mnt/foo\tufs\t2\tyes\t-\n" }
let(:vfstab_file_contents) { [other_mount].join("\n") }
diff --git a/spec/unit/provider/mount/windows_spec.rb b/spec/unit/provider/mount/windows_spec.rb
index fdb44836b5..aeff294347 100644
--- a/spec/unit/provider/mount/windows_spec.rb
+++ b/spec/unit/provider/mount/windows_spec.rb
@@ -29,8 +29,8 @@ class Chef
end
end
-GUID = "\\\\?\\Volume{578e72b5-6e70-11df-b5c5-000c29d4a7d9}\\"
-REMOTE = "\\\\server-name\\path"
+GUID = "\\\\?\\Volume{578e72b5-6e70-11df-b5c5-000c29d4a7d9}\\".freeze
+REMOTE = "\\\\server-name\\path".freeze
describe Chef::Provider::Mount::Windows do
before(:each) do
@@ -99,10 +99,10 @@ describe Chef::Provider::Mount::Windows do
end
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)
+ expect(@vol).to receive(:add).with(remote: @new_resource.device,
+ username: @new_resource.username,
+ domainname: @new_resource.domain,
+ password: @new_resource.password)
@provider.mount_fs
end
diff --git a/spec/unit/provider/ohai_spec.rb b/spec/unit/provider/ohai_spec.rb
index fad08ba589..518523dca2 100644
--- a/spec/unit/provider/ohai_spec.rb
+++ b/spec/unit/provider/ohai_spec.rb
@@ -29,16 +29,16 @@ describe Chef::Provider::Ohai do
@platform_version = "example-platform"
Chef::Config[:node_name] = @fqdn
mock_ohai = {
- :fqdn => @fqdn,
- :hostname => @hostname,
- :platform => @platform,
- :platform_version => @platform_version,
- :data => {
- :origdata => "somevalue",
+ fqdn: @fqdn,
+ hostname: @hostname,
+ platform: @platform,
+ platform_version: @platform_version,
+ data: {
+ origdata: "somevalue",
},
- :data2 => {
- :origdata => "somevalue",
- :newdata => "somevalue",
+ data2: {
+ origdata: "somevalue",
+ newdata: "somevalue",
},
}
allow(mock_ohai).to receive(:all_plugins).and_return(true)
diff --git a/spec/unit/provider/osx_profile_spec.rb b/spec/unit/provider/osx_profile_spec.rb
index a1dcf3ecd6..08d2eebdc4 100644
--- a/spec/unit/provider/osx_profile_spec.rb
+++ b/spec/unit/provider/osx_profile_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Provider::OsxProfile do
let(:shell_out_success) do
- double("shell_out", :exitstatus => 0, :error? => false)
+ double("shell_out", exitstatus: 0, error?: false)
end
describe "action_create" do
let(:node) { Chef::Node.new }
@@ -116,7 +116,7 @@ describe Chef::Provider::OsxProfile do
allow(provider).to receive(:generate_tempfile).and_return(tempfile)
allow(provider).to receive(:get_installed_profiles).and_call_original
allow(provider).to receive(:read_plist).and_return(all_profiles)
- expect(provider).to receive(:shell_out!).with("profiles -P -o '/tmp/allprofiles.plist'")
+ expect(provider).to receive(:shell_out_compacted!).with("profiles", "-P", "-o", "/tmp/allprofiles.plist")
provider.load_current_resource
end
@@ -139,6 +139,7 @@ describe Chef::Provider::OsxProfile do
new_resource.profile test_profile
allow(provider).to receive(:get_installed_profiles).and_return(no_profiles)
provider.load_current_resource
+ expect(provider).to receive(:install_profile)
expect { provider.run_action(:install) }.to_not raise_error
end
@@ -154,6 +155,7 @@ describe Chef::Provider::OsxProfile do
new_resource.profile test_profile
all_profiles["_computerlevel"][1]["ProfileUUID"] = "1781fbec-3325-565f-9022-9bb39245d4dd"
provider.load_current_resource
+ expect(provider).to receive(:install_profile)
expect { provider.run_action(:install) }.to_not raise_error
end
@@ -164,7 +166,7 @@ describe Chef::Provider::OsxProfile do
all_profiles["_computerlevel"][1]["ProfileUUID"] = "1781fbec-3325-565f-9022-9bb39245d4dd"
provider.load_current_resource
allow(provider).to receive(:write_profile_to_disk).and_return(profile_path)
- expect(provider).to receive(:shell_out).with("profiles -I -F '#{profile_path}'").and_return(shell_out_success)
+ expect(provider).to receive(:shell_out_compacted).with("profiles", "-I", "-F", profile_path).and_return(shell_out_success)
provider.action_install()
end
@@ -248,7 +250,7 @@ describe Chef::Provider::OsxProfile do
new_resource.identifier "com.testprofile.screensaver"
new_resource.action(:remove)
provider.load_current_resource
- expect(provider).to receive(:shell_out).with("profiles -R -p '#{new_resource.identifier}'").and_return(shell_out_success)
+ expect(provider).to receive(:shell_out_compacted).with("profiles", "-R", "-p", new_resource.identifier).and_return(shell_out_success)
provider.action_remove()
end
end
diff --git a/spec/unit/provider/package/apt_spec.rb b/spec/unit/provider/package/apt_spec.rb
index 46ae7fcadc..05be08f332 100644
--- a/spec/unit/provider/package/apt_spec.rb
+++ b/spec/unit/provider/package/apt_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,461 +20,513 @@ require "spec_helper"
require "ostruct"
describe Chef::Provider::Package::Apt do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
# XXX: sorry this is ugly and was done quickly to get 12.0.2 out, this file needs a rewrite to use
# 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
+ @run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
+ @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
+
+ @status = double("Status", exitstatus: 0)
+ @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
+ @stdin = StringIO.new
+ @stdout = <<~PKG_STATUS
+ irssi:
+ Installed: (none)
+ Candidate: 0.8.14-1ubuntu4
+ Version table:
+ 0.8.14-1ubuntu4 0
+ 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)
+ @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_compacted!).with(
+ "apt-cache", "policy", @new_resource.package_name,
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(@shell_out)
+ @provider.load_current_resource
+
+ current_resource = @provider.current_resource
+ expect(current_resource).to be_a(Chef::Resource::Package)
+ expect(current_resource.name).to eq("irssi")
+ expect(current_resource.package_name).to eq("irssi")
+ expect(current_resource.version).to eql([nil])
+ end
+
+ it "should set the installed version if package has one" do
+ @stdout.replace(<<~INSTALLED)
+ sudo:
+ Installed: 1.7.2p1-1ubuntu5.3
+ Candidate: 1.7.2p1-1ubuntu5.3
+ Version table:
+ *** 1.7.2p1-1ubuntu5.3 0
+ 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
+ 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
+ 100 /var/lib/dpkg/status
+ 1.7.2p1-1ubuntu5 0
+ 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages
+ INSTALLED
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
+ @provider.load_current_resource
+ expect(@provider.current_resource.version).to eq(["1.7.2p1-1ubuntu5.3"])
+ expect(@provider.candidate_version).to eql(["1.7.2p1-1ubuntu5.3"])
+ end
+
+ # it is the superclasses responsibility to throw most exceptions
+ it "if the package does not exist in the cache sets installed + candidate version to nil" do
+ @new_resource.package_name("conic-smarms")
+ policy_out = <<~POLICY_STDOUT
+ N: Unable to locate package conic-smarms
+ POLICY_STDOUT
+ policy = double(stdout: policy_out, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "policy", "conic-smarms",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(policy)
+ showpkg_out = <<~SHOWPKG_STDOUT
+ N: Unable to locate package conic-smarms
+ SHOWPKG_STDOUT
+ showpkg = double(stdout: showpkg_out, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "showpkg", "conic-smarms",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(showpkg)
+ @provider.load_current_resource
+ end
+
+ # libmysqlclient-dev is a real package in newer versions of debian + ubuntu
+ # 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
+ libmysqlclient15-dev:
+ Installed: (none)
+ Candidate: (none)
+ Version table:
+ VPKG_STDOUT
+ virtual_package = double(stdout: virtual_package_out, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "policy", "libmysqlclient15-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(virtual_package)
+ showpkg_out = <<~SHOWPKG_STDOUT
+ Package: libmysqlclient15-dev
+ Versions:
+
+ Reverse Depends:
+ libmysqlclient-dev,libmysqlclient15-dev
+ libmysqlclient-dev,libmysqlclient15-dev
+ libmysqlclient-dev,libmysqlclient15-dev
+ libmysqlclient-dev,libmysqlclient15-dev
+ libmysqlclient-dev,libmysqlclient15-dev
+ libmysqlclient-dev,libmysqlclient15-dev
+ Dependencies:
+ Provides:
+ Reverse Provides:
+ 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)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "showpkg", "libmysqlclient15-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(showpkg)
+ real_package_out = <<~RPKG_STDOUT
+ libmysqlclient-dev:
+ Installed: 5.1.41-3ubuntu12.10
+ Candidate: 5.1.41-3ubuntu12.10
+ Version table:
+ *** 5.1.41-3ubuntu12.10 0
+ 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
+ 100 /var/lib/dpkg/status
+ 5.1.41-3ubuntu12.7 0
+ 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
+ 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)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "policy", "libmysqlclient-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(real_package)
+ @provider.load_current_resource
+ end
+
+ 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
+ mp3-decoder:
+ Installed: (none)
+ Candidate: (none)
+ Version table:
+ VPKG_STDOUT
+ virtual_package = double(stdout: virtual_package_out, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "policy", "mp3-decoder",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(virtual_package)
+ showpkg_out = <<~SHOWPKG_STDOUT
+ Package: mp3-decoder
+ Versions:
+
+ Reverse Depends:
+ nautilus,mp3-decoder
+ vux,mp3-decoder
+ plait,mp3-decoder
+ ecasound,mp3-decoder
+ nautilus,mp3-decoder
+ Dependencies:
+ Provides:
+ Reverse Provides:
+ vlc-nox 1.0.6-1ubuntu1.8
+ vlc 1.0.6-1ubuntu1.8
+ vlc-nox 1.0.6-1ubuntu1
+ vlc 1.0.6-1ubuntu1
+ 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)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "showpkg", "mp3-decoder",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(showpkg)
+ expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
+ end
+
+ it "should run apt-cache policy with the default_release option, if there is one on the resource" do
+ @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
+ @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
+
+ @new_resource.default_release("lenny-backports")
+ @new_resource.provider(nil)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "-o", "APT::Default-Release=lenny-backports", "policy", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ ).and_return(@shell_out)
+ @provider.load_current_resource
+ end
+
+ it "raises an exception if a source is specified (CHEF-5113)" do
+ @new_resource.source "pluto"
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-cache", "policy", @new_resource.package_name,
+ env: { "DEBIAN_FRONTEND" => "noninteractive" } ,
+ timeout: @timeout
+ ).and_return(@shell_out)
+ expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
+ end
+ end
+
+ context "after loading the current resource" do
+ before do
+ @current_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
+ @provider.current_resource = @current_resource
+ allow(@provider).to receive(:package_data).and_return({
+ "irssi" => {
+ virtual: false,
+ candidate_version: "0.8.12-7",
+ installed_version: nil,
+ },
+ "libmysqlclient15-dev" => {
+ virtual: true,
+ candidate_version: nil,
+ installed_version: nil,
+ },
+ })
+ end
+
+ describe "install_package" do
+ it "should run apt-get install with the package name and version" do
+ expect(@provider).to receive(:shell_out_compacted!). with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.install_package(["irssi"], ["0.8.12-7"])
+ end
+
+ it "should run apt-get install with the package name and version and options if specified" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "--force-yes", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @new_resource.options("--force-yes")
+ @provider.install_package(["irssi"], ["0.8.12-7"])
+ end
+
+ it "should run apt-get install with the package name and version and default_release if there is one and provider is explicitly defined" do
+ @new_resource = nil
+ @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
+ @new_resource.default_release("lenny-backports")
+ @new_resource.provider = nil
+ @provider.new_resource = @new_resource
+
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "-o", "APT::Default-Release=lenny-backports", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+
+ @provider.install_package(["irssi"], ["0.8.12-7"])
+ end
+
+ it "should run apt-get install with the package name and quotes options if specified" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "--force-yes", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confnew", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @new_resource.options('--force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew"')
+ @provider.install_package(["irssi"], ["0.8.12-7"])
+ end
+ end
+
+ describe Chef::Resource::AptPackage, "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"])
+ end
+ end
+
+ describe Chef::Resource::AptPackage, "remove_package" do
+
+ it "should run apt-get remove with the package name" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "remove", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.remove_package(["irssi"], ["0.8.12-7"])
+ end
+
+ it "should run apt-get remove with the package name and options if specified" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "--force-yes", "remove", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @new_resource.options("--force-yes")
+
+ @provider.remove_package(["irssi"], ["0.8.12-7"])
+ end
+ end
+
+ describe "when purging a package" do
+
+ it "should run apt-get purge with the package name" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "purge", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.purge_package(["irssi"], ["0.8.12-7"])
+ end
+
+ it "should run apt-get purge with the package name and options if specified" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "--force-yes", "purge", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @new_resource.options("--force-yes")
+
+ @provider.purge_package(["irssi"], ["0.8.12-7"])
+ end
+ end
+
+ describe "when preseeding a package" do
before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @new_resource = resource_klass.new("irssi", @run_context)
-
- @status = double("Status", :exitstatus => 0)
- @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
- @stdin = StringIO.new
- @stdout = <<-PKG_STATUS
-irssi:
- Installed: (none)
- Candidate: 0.8.14-1ubuntu4
- Version table:
- 0.8.14-1ubuntu4 0
- 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)
- @timeout = 900
+ allow(@provider).to receive(:get_preseed_file).and_return("/tmp/irssi-0.8.12-7.seed")
+ end
+
+ it "should get the full path to the preseed response file" do
+ file = "/tmp/irssi-0.8.12-7.seed"
+
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "debconf-set-selections", "/tmp/irssi-0.8.12-7.seed",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+
+ @provider.preseed_package(file)
+ end
+
+ it "should run debconf-set-selections on the preseed file if it has changed" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "debconf-set-selections", "/tmp/irssi-0.8.12-7.seed",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ file = @provider.get_preseed_file("irssi", "0.8.12-7")
+ @provider.preseed_package(file)
+ end
+
+ it "should not run debconf-set-selections if the preseed file has not changed" do
+ allow(@provider).to receive(:check_all_packages_state)
+ @current_resource.version "0.8.11"
+ @new_resource.response_file "/tmp/file"
+ allow(@provider).to receive(:get_preseed_file).and_return(false)
+ expect(@provider).not_to receive(:shell_out_compacted!)
+ @provider.run_action(:reconfig)
+ end
+ end
+
+ describe "when reconfiguring a package" do
+ it "should run dpkg-reconfigure package" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "dpkg-reconfigure", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.reconfig_package("irssi", "0.8.12-7")
+ end
+ end
+
+ describe "when locking a package" do
+ it "should run apt-mark hold package" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-mark", "hold", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.lock_package("irssi", "0.8.12-7")
+ end
+ it "should not lock if the package is already locked" do
+ allow(@provider).to receive(:shell_out_compacted!).with(
+ "apt-mark", "showhold", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "irssi")
+ )
+ expect(logger).to receive(:trace).with("#{@provider.new_resource} is already locked")
+
+ @provider.action_lock
+ end
+ end
+
+ describe "when unlocking a package" do
+ it "should run apt-mark unhold package" do
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-mark", "unhold", "irssi",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.unlock_package("irssi", "0.8.12-7")
+ end
+ it "should not unlock if the package is already unlocked" do
+ allow(@provider).to receive(:shell_out_compacted!).with(
+ "apt-mark", "showhold", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "")
+ )
+ expect(logger).to receive(:trace).with("#{@provider.new_resource} is already unlocked")
+
+ @provider.action_unlock
+ end
+ end
+
+ describe "when installing a virtual package" do
+ it "should install the package without specifying a version" do
+ @provider.package_data["libmysqlclient15-dev"][:virtual] = true
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "install", "libmysqlclient15-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.install_package(["libmysqlclient15-dev"], ["not_a_real_version"])
+ end
+ end
+
+ describe "when removing a virtual package" do
+ it "should remove the resolved name instead of the virtual package name" do
+ expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "remove", "libmysqlclient-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.remove_package(["libmysqlclient15-dev"], ["not_a_real_version"])
+ end
+ end
+
+ describe "when purging a virtual package" do
+ it "should purge the resolved name instead of the virtual package name" do
+ expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "purge", "libmysqlclient-dev",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.purge_package(["libmysqlclient15-dev"], ["not_a_real_version"])
end
+ 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,
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(@shell_out)
- @provider.load_current_resource
-
- current_resource = @provider.current_resource
- expect(current_resource).to be_a(Chef::Resource::Package)
- expect(current_resource.name).to eq("irssi")
- expect(current_resource.package_name).to eq("irssi")
- expect(current_resource.version).to eql([nil])
- end
-
- it "should set the installed version if package has one" do
- @stdout.replace(<<-INSTALLED)
-sudo:
- Installed: 1.7.2p1-1ubuntu5.3
- Candidate: 1.7.2p1-1ubuntu5.3
- Version table:
- *** 1.7.2p1-1ubuntu5.3 0
- 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
- 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
- 100 /var/lib/dpkg/status
- 1.7.2p1-1ubuntu5 0
- 500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages
- INSTALLED
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
- @provider.load_current_resource
- expect(@provider.current_resource.version).to eq(["1.7.2p1-1ubuntu5.3"])
- expect(@provider.candidate_version).to eql(["1.7.2p1-1ubuntu5.3"])
- end
-
- # it is the superclasses responsibility to throw most exceptions
- it "if the package does not exist in the cache sets installed + candidate version to nil" do
- @new_resource.package_name("conic-smarms")
- policy_out = <<-POLICY_STDOUT
-N: Unable to locate package conic-smarms
- POLICY_STDOUT
- policy = double(:stdout => policy_out, :exitstatus => 0)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "policy", "conic-smarms",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(policy)
- showpkg_out = <<-SHOWPKG_STDOUT
-N: Unable to locate package conic-smarms
- SHOWPKG_STDOUT
- showpkg = double(:stdout => showpkg_out, :exitstatus => 0)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "showpkg", "conic-smarms",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(showpkg)
- @provider.load_current_resource
- end
-
- # libmysqlclient-dev is a real package in newer versions of debian + ubuntu
- # 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
-libmysqlclient15-dev:
- Installed: (none)
- Candidate: (none)
- Version table:
- VPKG_STDOUT
- virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "policy", "libmysqlclient15-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(virtual_package)
- showpkg_out = <<-SHOWPKG_STDOUT
-Package: libmysqlclient15-dev
-Versions:
-
-Reverse Depends:
- libmysqlclient-dev,libmysqlclient15-dev
- libmysqlclient-dev,libmysqlclient15-dev
- libmysqlclient-dev,libmysqlclient15-dev
- libmysqlclient-dev,libmysqlclient15-dev
- libmysqlclient-dev,libmysqlclient15-dev
- libmysqlclient-dev,libmysqlclient15-dev
-Dependencies:
-Provides:
-Reverse Provides:
-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)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "showpkg", "libmysqlclient15-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(showpkg)
- real_package_out = <<-RPKG_STDOUT
-libmysqlclient-dev:
- Installed: 5.1.41-3ubuntu12.10
- Candidate: 5.1.41-3ubuntu12.10
- Version table:
- *** 5.1.41-3ubuntu12.10 0
- 500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
- 100 /var/lib/dpkg/status
- 5.1.41-3ubuntu12.7 0
- 500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
- 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)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "policy", "libmysqlclient-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(real_package)
- @provider.load_current_resource
- end
-
- 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
-mp3-decoder:
- Installed: (none)
- Candidate: (none)
- Version table:
- VPKG_STDOUT
- virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "policy", "mp3-decoder",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(virtual_package)
- showpkg_out = <<-SHOWPKG_STDOUT
-Package: mp3-decoder
-Versions:
-
-Reverse Depends:
- nautilus,mp3-decoder
- vux,mp3-decoder
- plait,mp3-decoder
- ecasound,mp3-decoder
- nautilus,mp3-decoder
-Dependencies:
-Provides:
-Reverse Provides:
-vlc-nox 1.0.6-1ubuntu1.8
-vlc 1.0.6-1ubuntu1.8
-vlc-nox 1.0.6-1ubuntu1
-vlc 1.0.6-1ubuntu1
-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)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "showpkg", "mp3-decoder",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(showpkg)
- expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
- end
-
- it "should run apt-cache policy with the default_release option, if there is one on the resource" do
- @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
- @provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
-
- @new_resource.default_release("lenny-backports")
- @new_resource.provider(nil)
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "-o", "APT::Default-Release=lenny-backports", "policy", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- ).and_return(@shell_out)
- @provider.load_current_resource
- end
-
- it "raises an exception if a source is specified (CHEF-5113)" do
- @new_resource.source "pluto"
- expect(@provider).to receive(:shell_out!).with(
- "apt-cache", "policy", @new_resource.package_name,
- :env => { "DEBIAN_FRONTEND" => "noninteractive" } ,
- :timeout => @timeout
- ).and_return(@shell_out)
- expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
- end
+ describe "when installing multiple packages" do
+ it "can install a virtual package followed by a non-virtual package" do
+ # https://github.com/chef/chef/issues/2914
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "install", "libmysqlclient15-dev", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.install_package(["libmysqlclient15-dev", "irssi"], ["not_a_real_version", "0.8.12-7"])
end
+ end
- context "after loading the current resource" do
- before do
- @current_resource = resource_klass.new("irssi", @run_context)
- @provider.current_resource = @current_resource
- allow(@provider).to receive(:package_data).and_return({
- "irssi" => {
- virtual: false,
- candidate_version: "0.8.12-7",
- installed_version: nil,
- },
- "libmysqlclient15-dev" => {
- virtual: true,
- candidate_version: nil,
- installed_version: nil,
- },
- })
- end
-
- describe "install_package" do
- 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" },
- :timeout => @timeout
- )
- @provider.install_package(["irssi"], ["0.8.12-7"])
- end
-
- 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" },
- :timeout => @timeout
- )
- @new_resource.options("--force-yes")
- @provider.install_package(["irssi"], ["0.8.12-7"])
- end
-
- it "should run apt-get install with the package name and version and default_release if there is one and provider is explicitly defined" do
- @new_resource = nil
- @new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
- @new_resource.default_release("lenny-backports")
- @new_resource.provider = nil
- @provider.new_resource = @new_resource
-
- 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" },
- :timeout => @timeout
- )
-
- @provider.install_package(["irssi"], ["0.8.12-7"])
- end
-
- it "should run apt-get install with the package name and quotes options if specified" do
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "--force-yes", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confnew", "install", "irssi=0.8.12-7",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @new_resource.options('--force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew"')
- @provider.install_package(["irssi"], ["0.8.12-7"])
- end
- 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"])
- end
- 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" },
- :timeout => @timeout
- )
- @provider.remove_package(["irssi"], ["0.8.12-7"])
- end
-
- it "should run apt-get remove with the package name and options if specified" do
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "--force-yes", "remove", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @new_resource.options("--force-yes")
-
- @provider.remove_package(["irssi"], ["0.8.12-7"])
- end
- 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",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.purge_package(["irssi"], ["0.8.12-7"])
- end
-
- it "should run apt-get purge with the package name and options if specified" do
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "--force-yes", "purge", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @new_resource.options("--force-yes")
-
- @provider.purge_package(["irssi"], ["0.8.12-7"])
- end
- end
-
- describe "when preseeding a package" do
- before(:each) do
- allow(@provider).to receive(:get_preseed_file).and_return("/tmp/irssi-0.8.12-7.seed")
- end
-
- it "should get the full path to the preseed response file" do
- file = "/tmp/irssi-0.8.12-7.seed"
-
- expect(@provider).to receive(:shell_out!).with(
- "debconf-set-selections", "/tmp/irssi-0.8.12-7.seed",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
-
- @provider.preseed_package(file)
- end
-
- 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" },
- :timeout => @timeout
- )
- file = @provider.get_preseed_file("irssi", "0.8.12-7")
- @provider.preseed_package(file)
- end
-
- it "should not run debconf-set-selections if the preseed file has not changed" do
- allow(@provider).to receive(:check_all_packages_state)
- @current_resource.version "0.8.11"
- @new_resource.response_file "/tmp/file"
- allow(@provider).to receive(:get_preseed_file).and_return(false)
- expect(@provider).not_to receive(:shell_out!)
- @provider.run_action(:reconfig)
- end
- end
-
- describe "when reconfiguring a package" do
- it "should run dpkg-reconfigure package" do
- expect(@provider).to receive(:shell_out!).with(
- "dpkg-reconfigure", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.reconfig_package("irssi", "0.8.12-7")
- end
- end
-
- describe "when locking a package" do
- it "should run apt-mark hold package" do
- expect(@provider).to receive(:shell_out!).with(
- "apt-mark", "hold", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.lock_package("irssi", "0.8.12-7")
- end
- end
-
- describe "when unlocking a package" do
- it "should run apt-mark unhold package" do
- expect(@provider).to receive(:shell_out!).with(
- "apt-mark", "unhold", "irssi",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.unlock_package("irssi", "0.8.12-7")
- end
- end
-
- describe "when installing a virtual package" do
- it "should install the package without specifying a version" do
- @provider.package_data["libmysqlclient15-dev"][:virtual] = true
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "install", "libmysqlclient15-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.install_package(["libmysqlclient15-dev"], ["not_a_real_version"])
- end
- end
-
- describe "when removing a virtual package" do
- it "should remove the resolved name instead of the virtual package name" do
- expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "remove", "libmysqlclient-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.remove_package(["libmysqlclient15-dev"], ["not_a_real_version"])
- end
- end
-
- describe "when purging a virtual package" do
- it "should purge the resolved name instead of the virtual package name" do
- expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "purge", "libmysqlclient-dev",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.purge_package(["libmysqlclient15-dev"], ["not_a_real_version"])
- end
- end
-
- describe "when installing multiple packages" do
- it "can install a virtual package followed by a non-virtual package" do
- # https://github.com/chef/chef/issues/2914
- expect(@provider).to receive(:shell_out!).with(
- "apt-get", "-q", "-y", "install", "libmysqlclient15-dev", "irssi=0.8.12-7",
- :env => { "DEBIAN_FRONTEND" => "noninteractive" },
- :timeout => @timeout
- )
- @provider.install_package(["libmysqlclient15-dev", "irssi"], ["not_a_real_version", "0.8.12-7"])
- end
- end
+ describe "#action_install" do
+ it "should run dpkg to compare versions if an existing version is installed" do
+ allow(@provider).to receive(:get_current_versions).and_return("1.4.0")
+ allow(@new_resource).to receive(:allow_downgrade).and_return(false)
+ expect(@provider).to receive(:shell_out_compacted).with(
+ "dpkg", "--compare-versions", "1.4.0", "gt", "0.8.12-7", timeout: 900
+ ).and_return(double(error?: false))
+ @provider.run_action(:upgrade)
+ end
+
+ it "should install the package if the installed version is older" do
+ allow(@provider).to receive(:get_current_versions).and_return("0.4.0")
+ allow(@new_resource).to receive(:allow_downgrade).and_return(false)
+ expect(@provider).to receive(:version_compare).and_return(-1)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.run_action(:upgrade)
+ end
+ it "should not compare versions if an existing version is not installed" do
+ allow(@provider).to receive(:get_current_versions).and_return(nil)
+ allow(@new_resource).to receive(:allow_downgrade).and_return(false)
+ expect(@provider).not_to receive(:version_compare)
+ expect(@provider).to receive(:shell_out_compacted!).with(
+ "apt-get", "-q", "-y", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confold", "install", "irssi=0.8.12-7",
+ env: { "DEBIAN_FRONTEND" => "noninteractive" },
+ timeout: @timeout
+ )
+ @provider.run_action(:upgrade)
end
end
end
diff --git a/spec/unit/provider/package/aix_spec.rb b/spec/unit/provider/package/bff_spec.rb
index 3c54c6a80c..7606092762 100644
--- a/spec/unit/provider/package/aix_spec.rb
+++ b/spec/unit/provider/package/bff_spec.rb
@@ -18,16 +18,18 @@
#
require "spec_helper"
-describe Chef::Provider::Package::Aix do
+describe Chef::Provider::Package::Bff do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
before(:each) do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@new_resource = Chef::Resource::Package.new("samba.base")
@new_resource.source("/tmp/samba.base")
- @provider = Chef::Provider::Package::Aix.new(@new_resource, @run_context)
+ @provider = Chef::Provider::Package::Bff.new(@new_resource, @run_context)
allow(::File).to receive(:exist?).with(@new_resource.source).and_return(true)
end
@@ -36,27 +38,27 @@ describe Chef::Provider::Package::Aix 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:"
- @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
- status = double("Status", :stdout => @bffinfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
+ status = double("Status", stdout: @bffinfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
@provider.load_current_resource
expect(@provider.current_resource.name).to eq("samba.base")
end
it "should set the current resource bff package name to the new resource bff package name" do
- status = double("Status", :stdout => @bffinfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
+ status = double("Status", stdout: @bffinfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("samba.base")
end
it "should raise an exception if a source is supplied but not found" do
- allow(@provider).to receive(:shell_out).and_return(@empty_status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@empty_status)
allow(::File).to receive(:exist?).with(@new_resource.source).and_return(false)
@provider.load_current_resource
@provider.define_resource_requirements
@@ -64,9 +66,9 @@ describe Chef::Provider::Package::Aix do
end
it "should get the source package version from lslpp if provided" do
- status = double("Status", :stdout => @bffinfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
+ status = double("Status", stdout: @bffinfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("samba.base")
@@ -76,10 +78,10 @@ describe Chef::Provider::Package::Aix do
it "should warn if the package is not a fileset" do
info = "samba.base:samba.base.samples:3.3.12.0::COMMITTED:I:Samba for AIX:
/etc/objrepos:samba.base:3.3.12.0::COMMITTED:I:Samba for AIX:"
- status = double("Status", :stdout => info, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
- expect(Chef::Log).to receive(:warn).once.with(%r{bff package by product name})
+ status = double("Status", stdout: info, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
+ expect(logger).to receive(:warn).once.with(%r{bff package by product name})
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("samba.base")
@@ -87,33 +89,33 @@ describe Chef::Provider::Package::Aix do
end
it "should return the current version installed if found by lslpp" do
- status = double("Status", :stdout => @bffinfo, :exitstatus => 0)
+ status = double("Status", stdout: @bffinfo, exitstatus: 0)
@stdout = StringIO.new(@bffinfo)
@stdin, @stderr = StringIO.new, StringIO.new
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(status)
@provider.load_current_resource
expect(@provider.current_resource.version).to eq("3.3.12.0")
end
it "should raise an exception if the source is not set but we are installing" do
- status = double("Status", :stdout => "", :exitstatus => 1, :format_for_exception => "")
+ status = double("Status", stdout: "", exitstatus: 1, format_for_exception: "")
@new_resource = Chef::Resource::Package.new("samba.base")
- @provider = Chef::Provider::Package::Aix.new(@new_resource, @run_context)
- allow(@provider).to receive(:shell_out).and_return(status)
+ @provider = Chef::Provider::Package::Bff.new(@new_resource, @run_context)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
end
it "should raise an exception if installp/lslpp fails to run" do
- status = double(:stdout => "", :exitstatus => -1, :format_for_exception => "")
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "", exitstatus: -1, format_for_exception: "")
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
end
it "should return a current resource with a nil version if the package is not found" do
- status = double("Status", :stdout => @bffinfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
- expect(@provider).to receive(:shell_out).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
+ status = double("Status", stdout: @bffinfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("lslpp", "-lcq", "samba.base", timeout: 900).and_return(@empty_status)
@provider.load_current_resource
expect(@provider.current_resource.version).to be_nil
end
@@ -121,8 +123,8 @@ describe Chef::Provider::Package::Aix do
it "should raise an exception if the source doesn't provide the requested package" do
wrongbffinfo = "/usr/lib/objrepos:openssl.base:0.9.8.2400::COMMITTED:I:Open Secure Socket Layer:
/etc/objrepos:openssl.base:0.9.8.2400::COMMITTED:I:Open Secure Socket Layer:"
- status = double("Status", :stdout => wrongbffinfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
+ status = double("Status", stdout: wrongbffinfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("installp", "-L", "-d", "/tmp/samba.base", timeout: 900).and_return(status)
expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
end
end
@@ -130,19 +132,19 @@ describe Chef::Provider::Package::Aix do
describe "candidate_version" do
it "should return the candidate_version variable if already setup" do
@provider.candidate_version = "3.3.12.0"
- expect(@provider).not_to receive(:shell_out)
+ expect(@provider).not_to receive(:shell_out_compacted)
@provider.candidate_version
end
it "should lookup the candidate_version if the variable is not already set" do
- status = double(:stdout => "", :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
@provider.candidate_version
end
it "should throw and exception if the exitstatus is not 0" do
- @status = double(:stdout => "", :exitstatus => 1, :format_for_exception => "")
- allow(@provider).to receive(:shell_out).and_return(@status)
+ @status = double(stdout: "", exitstatus: 1, format_for_exception: "")
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package)
end
@@ -150,34 +152,34 @@ describe Chef::Provider::Package::Aix do
describe "install and upgrade" do
it "should run installp -aYF -d with the package source to install" do
- expect(@provider).to receive(:shell_out!).with("installp", "-aYF", "-d", "/tmp/samba.base", "samba.base", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("installp", "-aYF", "-d", "/tmp/samba.base", "samba.base", timeout: 900)
@provider.install_package("samba.base", "3.3.12.0")
end
it "should run installp -aYF -d when the package is a path to install" do
@new_resource = Chef::Resource::Package.new("/tmp/samba.base")
- @provider = Chef::Provider::Package::Aix.new(@new_resource, @run_context)
+ @provider = Chef::Provider::Package::Bff.new(@new_resource, @run_context)
expect(@new_resource.source).to eq("/tmp/samba.base")
- expect(@provider).to receive(:shell_out!).with("installp", "-aYF", "-d", "/tmp/samba.base", "/tmp/samba.base", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("installp", "-aYF", "-d", "/tmp/samba.base", "/tmp/samba.base", timeout: 900)
@provider.install_package("/tmp/samba.base", "3.3.12.0")
end
it "should run installp with -eLogfile option." do
@new_resource.options("-e/tmp/installp.log")
- expect(@provider).to receive(:shell_out!).with("installp", "-aYF", "-e/tmp/installp.log", "-d", "/tmp/samba.base", "samba.base", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("installp", "-aYF", "-e/tmp/installp.log", "-d", "/tmp/samba.base", "samba.base", timeout: 900)
@provider.install_package("samba.base", "3.3.12.0")
end
end
describe "remove" do
it "should run installp -u samba.base to remove the package" do
- expect(@provider).to receive(:shell_out!).with("installp", "-u", "samba.base", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("installp", "-u", "samba.base", timeout: 900)
@provider.remove_package("samba.base", "3.3.12.0")
end
it "should run installp -u -e/tmp/installp.log with options -e/tmp/installp.log" do
@new_resource.options("-e/tmp/installp.log")
- expect(@provider).to receive(:shell_out!).with("installp", "-u", "-e/tmp/installp.log", "samba.base", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("installp", "-u", "-e/tmp/installp.log", "samba.base", timeout: 900)
@provider.remove_package("samba.base", "3.3.12.0")
end
diff --git a/spec/unit/provider/package/cab_spec.rb b/spec/unit/provider/package/cab_spec.rb
index 5c86f781f3..2ed40566f4 100644
--- a/spec/unit/provider/package/cab_spec.rb
+++ b/spec/unit/provider/package/cab_spec.rb
@@ -31,25 +31,25 @@ describe Chef::Provider::Package::Cab do
end
let(:installed_package_list_stdout) do
- <<-EOF
-Packages listing:
-Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
-Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
+ <<~EOF
+ Packages listing:
+ Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
+ Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
EOF
end
let(:package_version_stdout) do
- <<-EOF
-Package information:
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-State : Installed
-Dependency : Language Pack
-The operation completed successfully
+ <<~EOF
+ Package information:
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ State : Installed
+ Dependency : Language Pack
+ The operation completed successfully
EOF
end
before do
- new_resource.source = File.join("#{ENV['TEMP']}", "test6.1-kb2664825-v3-x64.cab")
+ new_resource.source = File.join((ENV["TEMP"]).to_s, "test6.1-kb2664825-v3-x64.cab")
installed_package_list_obj = double(stdout: installed_package_list_stdout)
allow(provider).to receive(:dism_command).with("/Get-Packages").and_return(installed_package_list_obj)
package_version_obj = double(stdout: package_version_stdout)
@@ -57,20 +57,20 @@ The operation completed successfully
end
def allow_package_info(package_path = nil, package_name = nil)
- get_package_info_stdout = <<-EOF
-Deployment Image Servicing and Management tool
-Version: 6.1.7600.16385
-
-Image Version: 6.1.7600.16385
-
-Package information:
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-Applicable : Yes
-Copyright : Microsoft Corporation
-Company : Microsoft Corporation
-State : Installed
-Dependency : Language Pack
-The operation completed successfully
+ get_package_info_stdout = <<~EOF
+ Deployment Image Servicing and Management tool
+ Version: 6.1.7600.16385
+
+ Image Version: 6.1.7600.16385
+
+ Package information:
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ Applicable : Yes
+ Copyright : Microsoft Corporation
+ Company : Microsoft Corporation
+ State : Installed
+ Dependency : Language Pack
+ The operation completed successfully
EOF
get_package_info_obj = double(stdout: get_package_info_stdout)
if package_path
@@ -81,30 +81,30 @@ The operation completed successfully
end
def allow_get_packages
- get_packages_stdout = <<-EOF
-Deployment Image Servicing and Management tool
-Version: 6.1.7600.16385
+ get_packages_stdout = <<~EOF
+ Deployment Image Servicing and Management tool
+ Version: 6.1.7600.16385
-Image Version: 6.1.7600.16385
+ Image Version: 6.1.7600.16385
-Packages listing:
+ Packages listing:
-Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
-State : Installed
-Release Type : Language Pack
-Install Time : 2/11/2015 11:33 PM
+ Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
+ State : Installed
+ Release Type : Language Pack
+ Install Time : 2/11/2015 11:33 PM
-Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
-State : Installed
-Release Type : Language Pack
-Install Time : 2/11/2015 11:33 PM
+ Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
+ State : Installed
+ Release Type : Language Pack
+ Install Time : 2/11/2015 11:33 PM
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-State : Installed
-Release Type : Feature Pack
-Install Time : 11/21/2010 3:40 AM
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ State : Installed
+ Release Type : Feature Pack
+ Install Time : 11/21/2010 3:40 AM
-The operation completed successfully.
+ The operation completed successfully.
EOF
get_packages_obj = double(stdout: get_packages_stdout)
allow(provider).to receive(:dism_command).with("/Get-Packages").and_return(get_packages_obj)
@@ -151,9 +151,9 @@ The operation completed successfully.
allow(Chef::FileCache).to receive(:create_cache_path).and_return(ENV["TEMP"])
path = provider.default_download_cache_path
if windows?
- expect(path).to be == File.join("#{ENV['TEMP']}", "\\", "Test6.1-KB2664825-v3-x64.cab")
+ expect(path).to be == File.join((ENV["TEMP"]).to_s, "\\", "Test6.1-KB2664825-v3-x64.cab")
else
- expect(path).to be == File.join("#{ENV['TEMP']}", "Test6.1-KB2664825-v3-x64.cab")
+ expect(path).to be == File.join((ENV["TEMP"]).to_s, "Test6.1-KB2664825-v3-x64.cab")
end
end
end
@@ -161,12 +161,12 @@ The operation completed successfully.
describe "#cab_file_source" do
context "when local file path is set" do
it "returns local cab file source path" do
- new_resource.source = File.join("#{ENV['TEMP']}", "test6.1-kb2664825-v3-x64.cab")
+ new_resource.source = File.join((ENV["TEMP"]).to_s, "test6.1-kb2664825-v3-x64.cab")
path = provider.cab_file_source
if windows?
- expect(path).to be == File.join("#{ENV['TEMP'].downcase}", "\\", "test6.1-kb2664825-v3-x64.cab")
+ expect(path).to be == File.join((ENV["TEMP"].downcase).to_s, "\\", "test6.1-kb2664825-v3-x64.cab")
else
- expect(path).to be == File.join("#{ENV['TEMP']}", "test6.1-kb2664825-v3-x64.cab")
+ expect(path).to be == File.join((ENV["TEMP"]).to_s, "test6.1-kb2664825-v3-x64.cab")
end
end
end
@@ -174,9 +174,9 @@ The operation completed successfully.
it "calls download_source_file method" do
new_resource.source = "https://www.something.com/test6.1-kb2664825-v3-x64.cab"
if windows?
- expect(provider).to receive(:download_source_file).and_return(File.join("#{ENV['TEMP'].downcase}", "\\", "test6.1-kb2664825-v3-x64.cab"))
+ expect(provider).to receive(:download_source_file).and_return(File.join((ENV["TEMP"].downcase).to_s, "\\", "test6.1-kb2664825-v3-x64.cab"))
else
- expect(provider).to receive(:download_source_file).and_return(File.join("#{ENV['TEMP']}", "test6.1-kb2664825-v3-x64.cab"))
+ expect(provider).to receive(:download_source_file).and_return(File.join((ENV["TEMP"]).to_s, "test6.1-kb2664825-v3-x64.cab"))
end
provider.cab_file_source
end
@@ -248,14 +248,14 @@ The operation completed successfully.
context "Invalid package source" do
def package_version_stdout
- package_version_stdout = <<-EOF
-Deployment Image Servicing and Management tool
-Version: 6.1.7600.16385
-Image Version: 6.1.7600.16385
-An error occurred trying to open - c:\\temp\\test6.1-KB2664825-v3-x64.cab Error: 0x80070003
-Error: 3
-The system cannot find the path specified.
-The DISM log file can be found at C:\\Windows\\Logs\\DISM\\dism.log.
+ package_version_stdout = <<~EOF
+ Deployment Image Servicing and Management tool
+ Version: 6.1.7600.16385
+ Image Version: 6.1.7600.16385
+ An error occurred trying to open - c:\\temp\\test6.1-KB2664825-v3-x64.cab Error: 0x80070003
+ Error: 3
+ The system cannot find the path specified.
+ The DISM log file can be found at C:\\Windows\\Logs\\DISM\\dism.log.
EOF
end
diff --git a/spec/unit/provider/package/chocolatey_spec.rb b/spec/unit/provider/package/chocolatey_spec.rb
index 68b121960c..48f8a562de 100644
--- a/spec/unit/provider/package/chocolatey_spec.rb
+++ b/spec/unit/provider/package/chocolatey_spec.rb
@@ -35,31 +35,33 @@ describe Chef::Provider::Package::Chocolatey do
# installed packages (ConEmu is upgradable)
let(:local_list_stdout) do
- <<-EOF
-Chocolatey v0.9.9.11
-chocolatey|0.9.9.11
-ConEmu|15.10.25.0
+ <<~EOF
+ Chocolatey v0.9.9.11
+ chocolatey|0.9.9.11
+ ConEmu|15.10.25.0
EOF
end
before do
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", { :returns => [0], :timeout => timeout }).and_return(local_list_obj)
+ local_list_obj = double(stdout: local_list_stdout)
+ allow(provider).to receive(:shell_out_compacted!).with("#{choco_exe} list -l -r", { returns: [0], timeout: timeout }).and_return(local_list_obj)
end
def allow_remote_list(package_names, args = nil)
- remote_list_stdout = <<-EOF
-Chocolatey v0.9.9.11
-chocolatey|0.9.9.11
-ConEmu|15.10.25.1
-Git|2.6.1
-Git|2.6.2
-munin-node|1.6.1.20130823
+ remote_list_stdout = <<~EOF
+ Chocolatey v0.9.9.11
+ chocolatey|0.9.9.11
+ ConEmu|15.10.25.1
+ Git|2.6.1
+ 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 -r #{package_names.join ' '}#{args}", { :returns => [0], timeout: timeout }).and_return(remote_list_obj)
+ package_names.each do |pkg|
+ allow(provider).to receive(:shell_out_compacted!).with("#{choco_exe} list -r #{pkg}#{args}", { returns: [0], timeout: timeout }).and_return(remote_list_obj)
+ end
end
describe "#initialize" do
@@ -180,7 +182,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -191,7 +193,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -220,7 +222,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y --version 15.10.25.1 conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -233,7 +235,7 @@ munin-node|1.6.1.20130823
new_resource.package_name(%w{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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y --version 15.10.25.1 conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -243,7 +245,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y --version 15.10.25.1 conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -253,8 +255,8 @@ munin-node|1.6.1.20130823
new_resource.package_name(%w{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", { :returns => [0], :timeout => timeout }).and_return(double)
- expect(provider).to receive(:shell_out!).with("#{choco_exe} install -y git", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y --version 15.10.25.1 conemu", { returns: [0], timeout: timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -263,7 +265,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y git munin-node", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -273,7 +275,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y -source localpackages git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -283,7 +285,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} install -y -force git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -317,7 +319,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -326,7 +328,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -335,7 +337,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -344,7 +346,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", { :returns => [0], :timeout => timeout })
+ expect(provider).not_to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y chocolatey", { returns: [0], timeout: timeout })
provider.run_action(:upgrade)
expect(new_resource).not_to be_updated_by_last_action
end
@@ -353,7 +355,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", { :returns => [0], :timeout => timeout })
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y --version 2.6.2 git", { returns: [0], timeout: timeout })
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -361,7 +363,7 @@ munin-node|1.6.1.20130823
it "upgrading multiple packages uses a single command" do
allow_remote_list(%w{conemu git})
new_resource.package_name(%w{conemu git})
- expect(provider).to receive(:shell_out!).with("#{choco_exe} upgrade -y conemu git", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} upgrade -y conemu git", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -413,7 +415,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} uninstall -y ConEmu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:remove)
expect(new_resource).to be_updated_by_last_action
end
@@ -422,7 +424,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", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} uninstall -y conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:remove)
expect(new_resource).to be_updated_by_last_action
end
@@ -432,24 +434,11 @@ munin-node|1.6.1.20130823
allow_remote_list(%w{git conemu})
new_resource.package_name(%w{git conemu})
provider.load_current_resource
- expect(provider).to receive(:shell_out!).with("#{choco_exe} uninstall -y conemu", { :returns => [0], :timeout => timeout }).and_return(double)
+ expect(provider).to receive(:shell_out_compacted!).with("#{choco_exe} uninstall -y conemu", { returns: [0], timeout: timeout }).and_return(double)
provider.run_action(:remove)
expect(new_resource).to be_updated_by_last_action
end
end
-
- describe "#action_uninstall" do
- it "should call :remove with a deprecation warning" do
- Chef::Config[:treat_deprecation_warnings_as_errors] = false
- expect(Chef::Log).to receive(:deprecation).with(/please use :remove/)
- allow_remote_list(["ConEmu"])
- new_resource.package_name("ConEmu")
- provider.load_current_resource
- expect(provider).to receive(:remove_package)
- provider.run_action(:uninstall)
- expect(new_resource).to be_updated_by_last_action
- end
- end
end
describe "behavior when Chocolatey is not installed" do
@@ -468,7 +457,7 @@ describe "behavior when Chocolatey is not installed" do
provider.instance_variable_set("@choco_install_path", nil)
# we don't care what this returns, but we have to let it be called.
- allow(provider).to receive(:shell_out!).and_return(double(:stdout => ""))
+ allow(provider).to receive(:shell_out_compacted!).and_return(double(stdout: ""))
end
let(:error_regex) do
diff --git a/spec/unit/provider/package/dpkg_spec.rb b/spec/unit/provider/package/dpkg_spec.rb
index e01e1d9cce..9df19f0f1b 100644
--- a/spec/unit/provider/package/dpkg_spec.rb
+++ b/spec/unit/provider/package/dpkg_spec.rb
@@ -31,28 +31,28 @@ describe Chef::Provider::Package::Dpkg do
let(:provider) { Chef::Provider::Package::Dpkg.new(new_resource, run_context) }
let(:dpkg_deb_version) { "1.11.4" }
- let(:dpkg_deb_status) { status = double(:stdout => "#{package}\t#{dpkg_deb_version}", :exitstatus => 0) }
+ let(:dpkg_deb_status) { status = double(stdout: "#{package}\t#{dpkg_deb_version}", exitstatus: 0) }
let(:dpkg_s_version) { "1.11.4-1ubuntu1" }
let(:dpkg_s_status) do
- stdout = <<-DPKG_S
-Package: #{package}
-Status: install ok installed
-Priority: important
-Section: web
-Installed-Size: 1944
-Maintainer: Ubuntu Core developers <ubuntu-devel-discuss@lists.ubuntu.com>
-Architecture: amd64
-Version: #{dpkg_s_version}
-Config-Version: #{dpkg_s_version}
-Depends: libc6 (>= 2.8~20080505), libssl0.9.8 (>= 0.9.8f-5)
-Conflicts: wget-ssl
+ stdout = <<~DPKG_S
+ Package: #{package}
+ Status: install ok installed
+ Priority: important
+ Section: web
+ Installed-Size: 1944
+ Maintainer: Ubuntu Core developers <ubuntu-devel-discuss@lists.ubuntu.com>
+ Architecture: amd64
+ Version: #{dpkg_s_version}
+ Config-Version: #{dpkg_s_version}
+ Depends: libc6 (>= 2.8~20080505), libssl0.9.8 (>= 0.9.8f-5)
+ Conflicts: wget-ssl
DPKG_S
- status = double(:stdout => stdout, :exitstatus => 1)
+ status = double(stdout: stdout, exitstatus: 1)
end
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_compacted!).with("dpkg-deb", "-W", source, timeout: 900).and_return(dpkg_deb_status)
+ allow(provider).to receive(:shell_out_compacted!).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
@@ -112,8 +112,8 @@ Conflicts: wget-ssl
describe "gets the source package version from dpkg-deb" do
def check_version(version)
- status = double(:stdout => "wget\t#{version}", :exitstatus => 0)
- expect(provider).to receive(:shell_out!).with("dpkg-deb", "-W", source, timeout: 900).and_return(status)
+ status = double(stdout: "wget\t#{version}", exitstatus: 0)
+ expect(provider).to receive(:shell_out_compacted!).with("dpkg-deb", "-W", source, timeout: 900).and_return(status)
provider.load_current_resource
expect(provider.current_resource.package_name).to eq(["wget"])
expect(provider.candidate_version).to eq([version])
@@ -165,34 +165,34 @@ Conflicts: wget-ssl
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_compacted!).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
it "on new debian/ubuntu we get an exit(1) and no stdout from dpkg -s for uninstalled" do
dpkg_s_status = double(
- exitstatus: 1, stdout: "", stderr: <<-EOF
-dpkg-query: package '#{package}' is not installed and no information is available
-Use dpkg --info (= dpkg-deb --info) to examine archive files,
-and dpkg --contents (= dpkg-deb --contents) to list their contents.
+ exitstatus: 1, stdout: "", stderr: <<~EOF
+ dpkg-query: package '#{package}' is not installed and no information is available
+ Use dpkg --info (= dpkg-deb --info) to examine archive files,
+ and dpkg --contents (= dpkg-deb --contents) to list their contents.
EOF
)
- expect(provider).to receive(:shell_out!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_return(dpkg_s_status)
+ expect(provider).to receive(:shell_out_compacted!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_return(dpkg_s_status)
provider.load_current_resource
expect(provider.current_resource.version).to eq([nil])
end
it "on old debian/ubuntu we get an exit(0) and we get info on stdout from dpkg -s for uninstalled" do
dpkg_s_status = double(
- exitstatus: 0, stderr: "", stdout: <<-EOF
-Package: #{package}
-Status: unknown ok not-installed
-Priority: extra
-Section: ruby
+ exitstatus: 0, stderr: "", stdout: <<~EOF
+ Package: #{package}
+ Status: unknown ok not-installed
+ Priority: extra
+ Section: ruby
EOF
)
- expect(provider).to receive(:shell_out!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_return(dpkg_s_status)
+ expect(provider).to receive(:shell_out_compacted!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_return(dpkg_s_status)
provider.load_current_resource
expect(provider.current_resource.version).to eq([nil])
end
@@ -201,13 +201,13 @@ Section: ruby
dpkg_s_status = double(
exitstatus: 3, stderr: "i am very, very angry with you. i'm very, very cross. go to your room.", stdout: ""
)
- expect(provider).to receive(:shell_out!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_raise(Mixlib::ShellOut::ShellCommandFailed)
+ expect(provider).to receive(:shell_out_compacted!).with("dpkg", "-s", package, returns: [0, 1], timeout: 900).and_raise(Mixlib::ShellOut::ShellCommandFailed)
expect { provider.load_current_resource }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
it "should raise an exception if dpkg-deb -W fails to run" do
- status = double(:stdout => "", :exitstatus => -1)
- expect(provider).to receive(:shell_out_compact_timeout!).with("dpkg-deb", "-W", "/tmp/wget_1.11.4-1ubuntu1_amd64.deb").and_raise(Mixlib::ShellOut::ShellCommandFailed)
+ status = double(stdout: "", exitstatus: -1)
+ expect(provider).to receive(:shell_out_compacted!).with("dpkg-deb", "-W", "/tmp/wget_1.11.4-1ubuntu1_amd64.deb", timeout: 900).and_raise(Mixlib::ShellOut::ShellCommandFailed)
expect { provider.load_current_resource }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
end
diff --git a/spec/unit/provider/package/freebsd/pkg_spec.rb b/spec/unit/provider/package/freebsd/pkg_spec.rb
index 4b3a94aa33..8c3e25a0f9 100644
--- a/spec/unit/provider/package/freebsd/pkg_spec.rb
+++ b/spec/unit/provider/package/freebsd/pkg_spec.rb
@@ -66,34 +66,34 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
describe "when querying for package state and attributes" do
before do
- #@new_resource = Chef::Resource::Package.new("zsh")
+ # @new_resource = Chef::Resource::Package.new("zsh")
- #@provider = Chef::Provider::Package::Freebsd::Pkg.new(@node, @new_resource)
+ # @provider = Chef::Provider::Package::Freebsd::Pkg.new(@node, @new_resource)
- #@status = double("Status", :exitstatus => 0)
- #@stdin = double("STDIN", :null_object => true)
- #@stdout = double("STDOUT", :null_object => true)
- #@stderr = double("STDERR", :null_object => true)
- #@pid = double("PID", :null_object => true)
+ # @status = double("Status", :exitstatus => 0)
+ # @stdin = double("STDIN", :null_object => true)
+ # @stdout = double("STDOUT", :null_object => true)
+ # @stderr = double("STDERR", :null_object => true)
+ # @pid = double("PID", :null_object => true)
end
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)
+ pkg_info = OpenStruct.new(stdout: "zsh-4.3.6_7")
+ expect(@provider).to receive(:shell_out_compacted!).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 eq("4.3.6_7")
end
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)
+ pkg_info = OpenStruct.new(stdout: "")
+ expect(@provider).to receive(:shell_out_compacted!).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
it "should return the port path for a valid port name" do
- whereis = OpenStruct.new(:stdout => "zsh: /usr/ports/shells/zsh")
- expect(@provider).to receive(:shell_out!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
+ whereis = OpenStruct.new(stdout: "zsh: /usr/ports/shells/zsh")
+ expect(@provider).to receive(:shell_out_compacted!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
allow(@provider).to receive(:port_name).and_return("zsh")
expect(@provider.port_path).to eq("/usr/ports/shells/zsh")
end
@@ -101,24 +101,24 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
# Not happy with the form of these tests as they are far too closely tied to the implementation and so very fragile.
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)
+ make_v = OpenStruct.new(stdout: "4.3.6\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).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
it "should figure out the package name when we have ports" 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)
- #@provider.should_receive(:ports_makefile_variable_value).with("PKGNAME").and_return("zsh-4.3.6_7")
+ make_v = OpenStruct.new(stdout: "zsh-4.3.6_7\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).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
end
describe Chef::Provider::Package::Freebsd::Pkg, "install_package" do
before(:each) do
- @cmd_result = OpenStruct.new(:status => true)
+ @cmd_result = OpenStruct.new(status: true)
@provider.current_resource = @current_resource
allow(@provider).to receive(:package_name).and_return("zsh")
@@ -127,22 +127,22 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
end
it "should run pkg_add -r with the package name" do
- expect(@provider).to receive(:shell_out!).with("pkg_add", "-r", "zsh", env: nil, timeout: 900).and_return(@cmd_result)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg_add", "-r", "zsh", env: nil, timeout: 900).and_return(@cmd_result)
@provider.install_package("zsh", "4.3.6_7")
end
end
describe Chef::Provider::Package::Freebsd::Pkg, "port path" do
before do
- #@node = Chef::Node.new
+ # @node = Chef::Node.new
@new_resource = Chef::Resource::Package.new("zsh")
@new_resource.cookbook_name = "adventureclub"
@provider = Chef::Provider::Package::Freebsd::Pkg.new(@new_resource, @run_context)
end
it "should figure out the port path from the package_name using whereis" do
- whereis = OpenStruct.new(:stdout => "zsh: /usr/ports/shells/zsh")
- expect(@provider).to receive(:shell_out!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
+ whereis = OpenStruct.new(stdout: "zsh: /usr/ports/shells/zsh")
+ expect(@provider).to receive(:shell_out_compacted!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
expect(@provider.port_path).to eq("/usr/ports/shells/zsh")
end
@@ -174,18 +174,18 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
allow(@provider).to receive(:package_name).and_return("ruby18-iconv")
allow(@provider).to receive(:latest_link_name).and_return("ruby18-iconv")
- @install_result = OpenStruct.new(:status => true)
+ @install_result = OpenStruct.new(status: true)
end
it "should run pkg_add -r with the package name" do
- expect(@provider).to receive(:shell_out!).with("pkg_add", "-r", "ruby18-iconv", env: nil, timeout: 900).and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg_add", "-r", "ruby18-iconv", env: nil, timeout: 900).and_return(@install_result)
@provider.install_package("ruby-iconv", "1.0")
end
end
describe Chef::Provider::Package::Freebsd::Pkg, "remove_package" do
before(:each) do
- @pkg_delete = OpenStruct.new(:status => true)
+ @pkg_delete = OpenStruct.new(status: true)
@new_resource.version "4.3.6_7"
@current_resource.version "4.3.6_7"
@provider.current_resource = @current_resource
@@ -193,7 +193,7 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
end
it "should run pkg_delete with the package name and version" do
- expect(@provider).to receive(:shell_out!).with("pkg_delete", "zsh-4.3.6_7", env: nil, timeout: 900).and_return(@pkg_delete)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg_delete", "zsh-4.3.6_7", env: nil, timeout: 900).and_return(@pkg_delete)
@provider.remove_package("zsh", "4.3.6_7")
end
end
@@ -212,15 +212,15 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
end
it "should return the port path for a valid port name" do
- whereis = OpenStruct.new(:stdout => "bonnie++: /usr/ports/benchmarks/bonnie++")
- expect(@provider).to receive(:shell_out!).with("whereis", "-s", "bonnie++", env: nil, timeout: 900).and_return(whereis)
+ whereis = OpenStruct.new(stdout: "bonnie++: /usr/ports/benchmarks/bonnie++")
+ expect(@provider).to receive(:shell_out_compacted!).with("whereis", "-s", "bonnie++", env: nil, timeout: 900).and_return(whereis)
allow(@provider).to receive(:port_name).and_return("bonnie++")
expect(@provider.port_path).to eq("/usr/ports/benchmarks/bonnie++")
end
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)
+ pkg_info = OpenStruct.new(stdout: "bonnie++-1.96")
+ expect(@provider).to receive(:shell_out_compacted!).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
@@ -252,8 +252,8 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
allow(@provider).to receive(:package_name).and_return("perl")
allow(@provider).to receive(:latest_link_name).and_return("perl")
- cmd = OpenStruct.new(:status => true)
- expect(@provider).to receive(:shell_out!).with("pkg_add", "-r", "perl", env: nil, timeout: 900).and_return(cmd)
+ cmd = OpenStruct.new(status: true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg_add", "-r", "perl", env: nil, timeout: 900).and_return(cmd)
@provider.install_package("perl5.8", "5.8.8_1")
end
@@ -266,8 +266,8 @@ describe Chef::Provider::Package::Freebsd::Pkg, "load_current_resource" do
allow(@provider).to receive(:package_name).and_return("mysql-server")
allow(@provider).to receive(:latest_link_name).and_return("mysql50-server")
- cmd = OpenStruct.new(:status => true)
- expect(@provider).to receive(:shell_out!).with("pkg_add", "-r", "mysql50-server", env: nil, timeout: 900).and_return(cmd)
+ cmd = OpenStruct.new(status: true)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg_add", "-r", "mysql50-server", env: nil, timeout: 900).and_return(cmd)
@provider.install_package("mysql50-server", "5.0.45_1")
end
end
diff --git a/spec/unit/provider/package/freebsd/pkgng_spec.rb b/spec/unit/provider/package/freebsd/pkgng_spec.rb
index 098052a057..13e5dd17fd 100644
--- a/spec/unit/provider/package/freebsd/pkgng_spec.rb
+++ b/spec/unit/provider/package/freebsd/pkgng_spec.rb
@@ -63,26 +63,26 @@ describe Chef::Provider::Package::Freebsd::Port do
describe "determining current installed version" do
before(:each) do
allow(@provider).to receive(:supports_pkgng?)
- @pkg_info = OpenStruct.new(:stdout => "zsh-3.1.7\nVersion : 3.1.7\n")
+ @pkg_info = OpenStruct.new(stdout: "zsh-3.1.7\nVersion : 3.1.7\n")
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_compacted!).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)
- expect(@provider).to receive(:shell_out!).with("pkg", "rquery", "%v", "zsh", env: nil, timeout: 900).and_return(pkg_query)
+ pkg_query = OpenStruct.new(stdout: "5.0.5\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "rquery", "%v", "zsh", env: nil, timeout: 900).and_return(pkg_query)
expect(@provider.candidate_version).to eq("5.0.5")
end
it "should query specified repository when given option" do
@provider.new_resource.options("-r LocalMirror") # This requires LocalMirror repo configuration.
- pkg_query = OpenStruct.new(:stdout => "5.0.3\n", :exitstatus => 0)
- expect(@provider).to receive(:shell_out!).with("pkg", "rquery", "-r", "LocalMirror", "%v", "zsh", env: nil, timeout: 900).and_return(pkg_query)
+ pkg_query = OpenStruct.new(stdout: "5.0.3\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "rquery", "-r", "LocalMirror", "%v", "zsh", env: nil, timeout: 900).and_return(pkg_query)
expect(@provider.candidate_version).to eq("5.0.3")
end
@@ -94,54 +94,54 @@ describe Chef::Provider::Package::Freebsd::Port do
describe "installing a binary package" do
before(:each) do
- @install_result = OpenStruct.new(:status => true)
+ @install_result = OpenStruct.new(status: true)
end
it "should handle package source from file" do
@provider.new_resource.source("/nas/pkg/repo/zsh-5.0.1.txz")
- expect(@provider).to receive(:shell_out!).
- with("pkg", "add", "/nas/pkg/repo/zsh-5.0.1.txz", env: { "LC_ALL" => nil }, timeout: 900).
- and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "add", "/nas/pkg/repo/zsh-5.0.1.txz", env: { "LC_ALL" => nil }, timeout: 900)
+ .and_return(@install_result)
@provider.install_package("zsh", "5.0.1")
end
it "should handle package source over ftp or http" do
@provider.new_resource.source("http://repo.example.com/zsh-5.0.1.txz")
- expect(@provider).to receive(:shell_out!).
- with("pkg", "add", "http://repo.example.com/zsh-5.0.1.txz", env: { "LC_ALL" => nil }, timeout: 900).
- and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "add", "http://repo.example.com/zsh-5.0.1.txz", env: { "LC_ALL" => nil }, timeout: 900)
+ .and_return(@install_result)
@provider.install_package("zsh", "5.0.1")
end
it "should handle a package name" do
- expect(@provider).to receive(:shell_out!).
- with("pkg", "install", "-y", "zsh", env: { "LC_ALL" => nil }, timeout: 900).and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "install", "-y", "zsh", env: { "LC_ALL" => nil }, timeout: 900).and_return(@install_result)
@provider.install_package("zsh", "5.0.1")
end
it "should handle a package name with a specified repo" do
@provider.new_resource.options("-r LocalMirror") # This requires LocalMirror repo configuration.
- expect(@provider).to receive(:shell_out!).
- with("pkg", "install", "-y", "-r", "LocalMirror", "zsh", env: { "LC_ALL" => nil }, timeout: 900).and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "install", "-y", "-r", "LocalMirror", "zsh", env: { "LC_ALL" => nil }, timeout: 900).and_return(@install_result)
@provider.install_package("zsh", "5.0.1")
end
end
describe "removing a binary package" do
before(:each) do
- @install_result = OpenStruct.new(:status => true)
+ @install_result = OpenStruct.new(status: true)
end
it "should call pkg delete" do
- expect(@provider).to receive(:shell_out!).
- with("pkg", "delete", "-y", "zsh-5.0.1", env: nil, timeout: 900).and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "delete", "-y", "zsh-5.0.1", env: nil, timeout: 900).and_return(@install_result)
@provider.remove_package("zsh", "5.0.1")
end
it "should not include repo option in pkg delete" do
@provider.new_resource.options("-r LocalMirror") # This requires LocalMirror repo configuration.
- expect(@provider).to receive(:shell_out!).
- with("pkg", "delete", "-y", "zsh-5.0.1", env: nil, timeout: 900).and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("pkg", "delete", "-y", "zsh-5.0.1", env: nil, timeout: 900).and_return(@install_result)
@provider.remove_package("zsh", "5.0.1")
end
end
diff --git a/spec/unit/provider/package/freebsd/port_spec.rb b/spec/unit/provider/package/freebsd/port_spec.rb
index 5c87483fa6..af5216dc04 100644
--- a/spec/unit/provider/package/freebsd/port_spec.rb
+++ b/spec/unit/provider/package/freebsd/port_spec.rb
@@ -62,22 +62,22 @@ describe Chef::Provider::Package::Freebsd::Port do
describe "determining current installed version" do
before(:each) do
- @pkg_info = OpenStruct.new(:stdout => "zsh-3.1.7\n")
+ @pkg_info = OpenStruct.new(stdout: "zsh-3.1.7\n")
end
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_compacted!).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
it "should check 'pkg info' if make supports WITH_PKGNG if freebsd version is < 1000017" do
- pkg_enabled = OpenStruct.new(:stdout => "yes\n")
+ pkg_enabled = OpenStruct.new(stdout: "yes\n")
[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(@new_resource).to receive(:shell_out_compacted!).with("make", "-V", "WITH_PKGNG", env: nil).and_return(pkg_enabled)
+ expect(@provider).to receive(:shell_out_compacted!).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
@@ -85,21 +85,21 @@ 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_compacted!).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
before(:each) do
- @port_version = OpenStruct.new(:stdout => "5.0.5\n", :exitstatus => 0)
+ @port_version = OpenStruct.new(stdout: "5.0.5\n", exitstatus: 0)
end
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).
- and_return(@port_version)
+ expect(@provider).to receive(:shell_out_compacted!).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
@@ -121,42 +121,42 @@ describe Chef::Provider::Package::Freebsd::Port do
end
it "should query system for path given just a name" do
- whereis = OpenStruct.new(:stdout => "zsh: /usr/ports/shells/zsh\n")
- expect(@provider).to receive(:shell_out!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
+ whereis = OpenStruct.new(stdout: "zsh: /usr/ports/shells/zsh\n")
+ expect(@provider).to receive(:shell_out_compacted!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
expect(@provider.port_dir).to eq("/usr/ports/shells/zsh")
end
it "should raise exception if not found" do
- whereis = OpenStruct.new(:stdout => "zsh:\n")
- expect(@provider).to receive(:shell_out!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
+ whereis = OpenStruct.new(stdout: "zsh:\n")
+ expect(@provider).to receive(:shell_out_compacted!).with("whereis", "-s", "zsh", env: nil, timeout: 900).and_return(whereis)
expect { @provider.port_dir }.to raise_error(Chef::Exceptions::Package, "Could not find port with the name zsh")
end
end
describe "building a binary package" do
before(:each) do
- @install_result = OpenStruct.new(:status => true)
+ @install_result = OpenStruct.new(status: true)
end
it "should run make install in port directory" do
allow(@provider).to receive(:port_dir).and_return("/usr/ports/shells/zsh")
- expect(@provider).to receive(:shell_out!).
- with("make", "-DBATCH", "install", "clean", :timeout => 1800, :cwd => "/usr/ports/shells/zsh", :env => nil).
- and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("make", "-DBATCH", "install", "clean", timeout: 1800, cwd: "/usr/ports/shells/zsh", env: nil)
+ .and_return(@install_result)
@provider.install_package("zsh", "5.0.5")
end
end
describe "removing a binary package" do
before(:each) do
- @install_result = OpenStruct.new(:status => true)
+ @install_result = OpenStruct.new(status: true)
end
it "should run make deinstall in port directory" do
allow(@provider).to receive(:port_dir).and_return("/usr/ports/shells/zsh")
- expect(@provider).to receive(:shell_out!).
- with("make", "deinstall", :timeout => 300, :cwd => "/usr/ports/shells/zsh", :env => nil).
- and_return(@install_result)
+ expect(@provider).to receive(:shell_out_compacted!)
+ .with("make", "deinstall", timeout: 300, cwd: "/usr/ports/shells/zsh", env: nil)
+ .and_return(@install_result)
@provider.remove_package("zsh", "5.0.5")
end
end
diff --git a/spec/unit/provider/package/homebrew_spec.rb b/spec/unit/provider/package/homebrew_spec.rb
index 572c54e83d..903aebc93e 100644
--- a/spec/unit/provider/package/homebrew_spec.rb
+++ b/spec/unit/provider/package/homebrew_spec.rb
@@ -20,7 +20,8 @@ require "spec_helper"
describe Chef::Provider::Package::Homebrew do
let(:node) { Chef::Node.new }
let(:events) { double("Chef::Events").as_null_object }
- let(:run_context) { double("Chef::RunContext", node: node, events: events) }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
let(:new_resource) { Chef::Resource::HomebrewPackage.new("emacs") }
let(:current_resource) { Chef::Resource::HomebrewPackage.new("emacs") }
@@ -172,16 +173,16 @@ describe Chef::Provider::Package::Homebrew do
describe "brew" do
before do
expect(provider).to receive(:find_homebrew_uid).and_return(homebrew_uid)
- expect(Etc).to receive(:getpwuid).with(homebrew_uid).and_return(OpenStruct.new(:name => "name", :dir => "/"))
+ expect(Etc).to receive(:getpwuid).with(homebrew_uid).and_return(OpenStruct.new(name: "name", dir: "/"))
end
it "passes a single to the brew command and return stdout" do
- allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "zombo"))
+ allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "zombo"))
expect(provider.brew).to eql("zombo")
end
it "takes multiple arguments as an array" do
- allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "homestarrunner"))
+ allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "homestarrunner"))
expect(provider.brew("info", "opts", "bananas")).to eql("homestarrunner")
end
@@ -189,7 +190,7 @@ describe Chef::Provider::Package::Homebrew do
let(:new_resource) { Chef::Resource::Package.new("emacs") }
it "does not try to read homebrew_user from Package, which does not have it" do
- allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(:stdout => "zombo"))
+ allow(provider).to receive(:shell_out!).and_return(OpenStruct.new(stdout: "zombo"))
expect(provider.brew).to eql("zombo")
end
end
diff --git a/spec/unit/provider/package/ips_spec.rb b/spec/unit/provider/package/ips_spec.rb
index 45111601fa..70e1c3fe32 100644
--- a/spec/unit/provider/package/ips_spec.rb
+++ b/spec/unit/provider/package/ips_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Bryan McLellan <btm@chef.io>
-# Copyright:: Copyright 2012-2017, Chef Software Inc.
+# Copyright:: Copyright 2012-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -35,125 +35,125 @@ describe Chef::Provider::Package::Ips do
def local_output
stdin = StringIO.new
stdout = ""
- stderr = <<-PKG_STATUS
-pkg: info: no packages matching the following patterns you specified are
-installed on the system. Try specifying -r to query remotely:
+ 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
+ crypto/gnupg
PKG_STATUS
- OpenStruct.new(:stdout => stdout, :stdin => stdin, :stderr => stderr, :status => @status, :exitstatus => 1)
+ 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
- State: Not Installed
- Publisher: omnios
- Version: 1.8.4.1 (1.8.4p1)
- Build Release: 5.11
- Branch: 0.151002
-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
+ stdout = <<~PKG_STATUS
+ Name: security/sudo
+ Summary: sudo - authority delegation tool
+ State: Not Installed
+ Publisher: omnios
+ Version: 1.8.4.1 (1.8.4p1)
+ Build Release: 5.11
+ Branch: 0.151002
+ 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 = ""
- OpenStruct.new(:stdout => stdout, :stdin => stdin, :stderr => stderr, :status => @status, :exitstatus => 0)
+ OpenStruct.new(stdout: stdout, stdin: stdin, stderr: stderr, status: @status, exitstatus: 0)
end
context "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("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
expect(Chef::Resource::IpsPackage).to receive(:new).and_return(@current_resource)
@provider.load_current_resource
end
it "should set the current resources package name to the new resources package name" do
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
@provider.load_current_resource
expect(@current_resource.package_name).to eq(@new_resource.package_name)
end
it "should run pkg info with the package name" do
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
@provider.load_current_resource
end
it "should set the installed version to nil on the current resource if package state is not installed" do
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
@provider.load_current_resource
expect(@current_resource.version).to be_nil
end
it "should set the installed version if package has one" do
local = local_output
- local.stdout = <<-INSTALLED
- Name: crypto/gnupg
- Summary: GNU Privacy Guard
- Description: A complete and free implementation of the OpenPGP Standard as
- defined by RFC4880.
- Category: Applications/System Utilities
- State: Installed
- Publisher: solaris
- Version: 2.0.17
- Build Release: 5.11
- Branch: 0.175.0.0.0.2.537
-Packaging Date: October 19, 2011 09:14:50 AM
- Size: 8.07 MB
- FMRI: pkg://solaris/crypto/gnupg@2.0.17,5.11-0.175.0.0.0.2.537:20111019T091450Z
+ local.stdout = <<~INSTALLED
+ Name: crypto/gnupg
+ Summary: GNU Privacy Guard
+ Description: A complete and free implementation of the OpenPGP Standard as
+ defined by RFC4880.
+ Category: Applications/System Utilities
+ State: Installed
+ Publisher: solaris
+ Version: 2.0.17
+ Build Release: 5.11
+ Branch: 0.175.0.0.0.2.537
+ Packaging Date: October 19, 2011 09:14:50 AM
+ Size: 8.07 MB
+ FMRI: pkg://solaris/crypto/gnupg@2.0.17,5.11-0.175.0.0.0.2.537:20111019T091450Z
INSTALLED
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
@provider.load_current_resource
expect(@current_resource.version).to eq("2.0.17")
end
it "should return the current resource" do
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote_output)
expect(@provider.load_current_resource).to eql(@current_resource)
end
end
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("pkg", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900)
@provider.install_package("crypto/gnupg", "2.0.17")
end
it "should run pkg install with the package name and version and options if specified" do
- expect(@provider).to receive(:shell_out!).with("pkg", "--no-refresh", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "--no-refresh", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900)
@new_resource.options "--no-refresh"
@provider.install_package("crypto/gnupg", "2.0.17")
end
it "raises an error if package fails to install" do
- expect(@provider).to receive(:shell_out!).with("pkg", "--no-refresh", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900).and_raise(Mixlib::ShellOut::ShellCommandFailed)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "--no-refresh", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900).and_raise(Mixlib::ShellOut::ShellCommandFailed)
@new_resource.options("--no-refresh")
expect { @provider.install_package("crypto/gnupg", "2.0.17") }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
it "should not include the human-readable version in the candidate_version" do
remote = remote_output
- remote.stdout = <<-PKG_STATUS
- Name: security/sudo
- Summary: sudo - authority delegation tool
- State: Not Installed
- Publisher: omnios
- Version: 1.8.4.1 (1.8.4p1)
- Build Release: 5.11
- Branch: 0.151002
-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
+ remote.stdout = <<~PKG_STATUS
+ Name: security/sudo
+ Summary: sudo - authority delegation tool
+ State: Not Installed
+ Publisher: omnios
+ Version: 1.8.4.1 (1.8.4p1)
+ Build Release: 5.11
+ Branch: 0.151002
+ 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
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote)
@provider.load_current_resource
expect(@current_resource.version).to be_nil
expect(@provider.candidate_version).to eql("1.8.4.1")
@@ -161,40 +161,40 @@ PKG_STATUS
it "should not upgrade the package if it is already installed" do
local = local_output
- local.stdout = <<-INSTALLED
- Name: crypto/gnupg
- Summary: GNU Privacy Guard
- Description: A complete and free implementation of the OpenPGP Standard as
- defined by RFC4880.
- Category: Applications/System Utilities
- State: Installed
- Publisher: solaris
- Version: 2.0.17
- Build Release: 5.11
- Branch: 0.175.0.0.0.2.537
-Packaging Date: October 19, 2011 09:14:50 AM
- Size: 8.07 MB
- FMRI: pkg://solaris/crypto/gnupg@2.0.17,5.11-0.175.0.0.0.2.537:20111019T091450Z
+ local.stdout = <<~INSTALLED
+ Name: crypto/gnupg
+ Summary: GNU Privacy Guard
+ Description: A complete and free implementation of the OpenPGP Standard as
+ defined by RFC4880.
+ Category: Applications/System Utilities
+ State: Installed
+ Publisher: solaris
+ Version: 2.0.17
+ Build Release: 5.11
+ Branch: 0.175.0.0.0.2.537
+ Packaging Date: October 19, 2011 09:14:50 AM
+ Size: 8.07 MB
+ FMRI: pkg://solaris/crypto/gnupg@2.0.17,5.11-0.175.0.0.0.2.537:20111019T091450Z
INSTALLED
remote = remote_output
- remote.stdout = <<-REMOTE
- Name: crypto/gnupg
- Summary: GNU Privacy Guard
- Description: A complete and free implementation of the OpenPGP Standard as
- defined by RFC4880.
- Category: Applications/System Utilities
- State: Not Installed
- Publisher: solaris
- Version: 2.0.18
- Build Release: 5.11
- Branch: 0.175.0.0.0.2.537
-Packaging Date: October 19, 2011 09:14:50 AM
- Size: 8.07 MB
- FMRI: pkg://solaris/crypto/gnupg@2.0.18,5.11-0.175.0.0.0.2.537:20111019T091450Z
+ remote.stdout = <<~REMOTE
+ Name: crypto/gnupg
+ Summary: GNU Privacy Guard
+ Description: A complete and free implementation of the OpenPGP Standard as
+ defined by RFC4880.
+ Category: Applications/System Utilities
+ State: Not Installed
+ Publisher: solaris
+ Version: 2.0.18
+ Build Release: 5.11
+ Branch: 0.175.0.0.0.2.537
+ Packaging Date: October 19, 2011 09:14:50 AM
+ Size: 8.07 MB
+ FMRI: pkg://solaris/crypto/gnupg@2.0.18,5.11-0.175.0.0.0.2.537:20111019T091450Z
REMOTE
- expect(@provider).to receive(:shell_out).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local)
- expect(@provider).to receive(:shell_out!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote)
+ expect(@provider).to receive(:shell_out_compacted).with("pkg", "info", @new_resource.package_name, timeout: 900).and_return(local)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "info", "-r", @new_resource.package_name, timeout: 900).and_return(remote)
expect(@provider).to receive(:install_package).exactly(0).times
@provider.run_action(:install)
end
@@ -205,7 +205,7 @@ REMOTE
end
it "should run pkg install with the --accept flag" do
- expect(@provider).to receive(:shell_out).with("pkg", "install", "-q", "--accept", "crypto/gnupg@2.0.17", timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "install", "-q", "--accept", "crypto/gnupg@2.0.17", timeout: 900).and_return(local_output)
@provider.install_package("crypto/gnupg", "2.0.17")
end
end
@@ -213,19 +213,19 @@ REMOTE
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("pkg", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900).and_return(local_output)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "install", "-q", "crypto/gnupg@2.0.17", timeout: 900).and_return(local_output)
@provider.upgrade_package("crypto/gnupg", "2.0.17")
end
end
context "when uninstalling a package" do
it "should run pkg uninstall with the package name and version" do
- expect(@provider).to receive(:shell_out!).with("pkg", "uninstall", "-q", "crypto/gnupg@2.0.17", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "uninstall", "-q", "crypto/gnupg@2.0.17", timeout: 900)
@provider.remove_package("crypto/gnupg", "2.0.17")
end
it "should run pkg uninstall with the package name and version and options if specified" do
- expect(@provider).to receive(:shell_out!).with("pkg", "--no-refresh", "uninstall", "-q", "crypto/gnupg@2.0.17", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("pkg", "--no-refresh", "uninstall", "-q", "crypto/gnupg@2.0.17", timeout: 900)
@new_resource.options "--no-refresh"
@provider.remove_package("crypto/gnupg", "2.0.17")
end
diff --git a/spec/unit/provider/package/macports_spec.rb b/spec/unit/provider/package/macports_spec.rb
index 4961f4c467..8b75e40d72 100644
--- a/spec/unit/provider/package/macports_spec.rb
+++ b/spec/unit/provider/package/macports_spec.rb
@@ -70,33 +70,33 @@ describe Chef::Provider::Package::Macports do
describe "current_installed_version" do
it "should return the current version if the package is installed" do
- stdout = <<EOF
-The following ports are currently installed:
- openssl @0.9.8k_0 (active)
+ stdout = <<~EOF
+ The following ports are currently installed:
+ openssl @0.9.8k_0 (active)
EOF
- status = double(:stdout => stdout, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: stdout, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
expect(@provider.current_installed_version).to eq("0.9.8k_0")
end
it "should return nil if a package is not currently installed" do
- status = double(:stdout => " \n", :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: " \n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
expect(@provider.current_installed_version).to be_nil
end
end
describe "macports_candidate_version" do
it "should return the latest available version of a given package" do
- status = double(:stdout => "version: 4.2.7\n", :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "version: 4.2.7\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
expect(@provider.macports_candidate_version).to eq("4.2.7")
end
it "should return nil if there is no version for a given package" do
- status = double(:stdout => "Error: port fadsfadsfads not found\n", :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "Error: port fadsfadsfads not found\n", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
expect(@provider.macports_candidate_version).to be_nil
end
end
@@ -105,7 +105,7 @@ EOF
it "should run the port install command with the correct version" do
expect(@current_resource).to receive(:version).and_return("4.1.6")
@provider.current_resource = @current_resource
- expect(@provider).to receive(:shell_out!).with("port", "install", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "install", "zsh", "@4.2.7", timeout: 900)
@provider.install_package("zsh", "4.2.7")
end
@@ -113,7 +113,7 @@ EOF
it "should not do anything if a package already exists with the same version" do
expect(@current_resource).to receive(:version).and_return("4.2.7")
@provider.current_resource = @current_resource
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.install_package("zsh", "4.2.7")
end
@@ -122,7 +122,7 @@ EOF
expect(@current_resource).to receive(:version).and_return("4.1.6")
@provider.current_resource = @current_resource
@new_resource.options("-f")
- expect(@provider).to receive(:shell_out!).with("port", "-f", "install", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "-f", "install", "zsh", "@4.2.7", timeout: 900)
@provider.install_package("zsh", "4.2.7")
end
@@ -130,36 +130,36 @@ EOF
describe "purge_package" do
it "should run the port uninstall command with the correct version" do
- expect(@provider).to receive(:shell_out!).with("port", "uninstall", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "uninstall", "zsh", "@4.2.7", timeout: 900)
@provider.purge_package("zsh", "4.2.7")
end
it "should purge the currently active version if no explicit version is passed in" do
- expect(@provider).to receive(:shell_out!).with("port", "uninstall", "zsh", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "uninstall", "zsh", timeout: 900)
@provider.purge_package("zsh", nil)
end
it "should add options to the port command when specified" do
@new_resource.options("-f")
- expect(@provider).to receive(:shell_out!).with("port", "-f", "uninstall", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "-f", "uninstall", "zsh", "@4.2.7", timeout: 900)
@provider.purge_package("zsh", "4.2.7")
end
end
describe "remove_package" do
it "should run the port deactivate command with the correct version" do
- expect(@provider).to receive(:shell_out!).with("port", "deactivate", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "deactivate", "zsh", "@4.2.7", timeout: 900)
@provider.remove_package("zsh", "4.2.7")
end
it "should remove the currently active version if no explicit version is passed in" do
- expect(@provider).to receive(:shell_out!).with("port", "deactivate", "zsh", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "deactivate", "zsh", timeout: 900)
@provider.remove_package("zsh", nil)
end
it "should add options to the port command when specified" do
@new_resource.options("-f")
- expect(@provider).to receive(:shell_out!).with("port", "-f", "deactivate", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "-f", "deactivate", "zsh", "@4.2.7", timeout: 900)
@provider.remove_package("zsh", "4.2.7")
end
end
@@ -169,7 +169,7 @@ EOF
expect(@current_resource).to receive(:version).at_least(:once).and_return("4.1.6")
@provider.current_resource = @current_resource
- expect(@provider).to receive(:shell_out!).with("port", "upgrade", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "upgrade", "zsh", "@4.2.7", timeout: 900)
@provider.upgrade_package("zsh", "4.2.7")
end
@@ -177,7 +177,7 @@ EOF
it "should not run the port upgrade command if the version is already installed" do
expect(@current_resource).to receive(:version).at_least(:once).and_return("4.2.7")
@provider.current_resource = @current_resource
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.upgrade_package("zsh", "4.2.7")
end
@@ -195,7 +195,7 @@ EOF
expect(@current_resource).to receive(:version).at_least(:once).and_return("4.1.6")
@provider.current_resource = @current_resource
- expect(@provider).to receive(:shell_out!).with("port", "-f", "upgrade", "zsh", "@4.2.7", timeout: 900)
+ expect(@provider).to receive(:shell_out_compacted!).with("port", "-f", "upgrade", "zsh", "@4.2.7", timeout: 900)
@provider.upgrade_package("zsh", "4.2.7")
end
diff --git a/spec/unit/provider/package/msu_spec.rb b/spec/unit/provider/package/msu_spec.rb
index b9091d757a..b2f0b22963 100644
--- a/spec/unit/provider/package/msu_spec.rb
+++ b/spec/unit/provider/package/msu_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Nimisha Sharad (<nimisha.sharad@msystechnologies.com>)
-# Copyright:: Copyright 2008-2016, Chef Software, Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -31,66 +31,66 @@ describe Chef::Provider::Package::Msu, :windows_only do
end
let(:installed_package_list_stdout) do
- <<-EOF
-Packages listing:
-Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
-Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
+ <<~EOF
+ Packages listing:
+ Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
+ Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
EOF
end
let(:package_version_stdout) do
- <<-EOF
-Package information:
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-State : Installed
-Dependency : Language Pack
-The operation completed successfully
+ <<~EOF
+ Package information:
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ State : Installed
+ Dependency : Language Pack
+ The operation completed successfully
EOF
end
let(:get_package_info_stdout) do
- <<-EOF
-Deployment Image Servicing and Management tool
-Version: 6.1.7600.16385
-
-Image Version: 6.1.7600.16385
-
-Package information:
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-Applicable : Yes
-Copyright : Microsoft Corporation
-Company : Microsoft Corporation
-State : Installed
-Dependency : Language Pack
-The operation completed successfully
+ <<~EOF
+ Deployment Image Servicing and Management tool
+ Version: 6.1.7600.16385
+
+ Image Version: 6.1.7600.16385
+
+ Package information:
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ Applicable : Yes
+ Copyright : Microsoft Corporation
+ Company : Microsoft Corporation
+ State : Installed
+ Dependency : Language Pack
+ The operation completed successfully
EOF
end
def allow_get_packages
- get_packages_stdout = <<-EOF
-Deployment Image Servicing and Management tool
-Version: 6.1.7600.16385
+ get_packages_stdout = <<~EOF
+ Deployment Image Servicing and Management tool
+ Version: 6.1.7600.16385
-Image Version: 6.1.7600.16385
+ Image Version: 6.1.7600.16385
-Packages listing:
+ Packages listing:
-Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
-State : Installed
-Release Type : Language Pack
-Install Time : 2/11/2015 11:33 PM
+ Package Identity : Package_for_KB2999486~31bf3856ad364e35~amd64~~6.1.9768.0
+ State : Installed
+ Release Type : Language Pack
+ Install Time : 2/11/2015 11:33 PM
-Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
-State : Installed
-Release Type : Language Pack
-Install Time : 2/11/2015 11:33 PM
+ Package Identity : Package_for_KB2994825~31bf3856ad364e35~amd64~~6.1.7601.0
+ State : Installed
+ Release Type : Language Pack
+ Install Time : 2/11/2015 11:33 PM
-Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
-State : Installed
-Release Type : Feature Pack
-Install Time : 11/21/2010 3:40 AM
+ Package Identity : Package_for_KB2664825~31bf3856ad364e35~amd64~~6.1.3.0
+ State : Installed
+ Release Type : Feature Pack
+ Install Time : 11/21/2010 3:40 AM
-The operation completed successfully.
+ The operation completed successfully.
EOF
get_packages_obj = double(stdout: get_packages_stdout)
allow_any_instance_of(Chef::Provider::Package::Cab).to receive(:dism_command).with("/Get-Packages").and_return(get_packages_obj)
@@ -243,7 +243,7 @@ The operation completed successfully.
describe "#extract_msu_contents" do
it "extracts the msu contents by using mixlib shellout" do
- expect(provider).to receive(:shell_out_with_timeout!).with("#{ENV['SYSTEMROOT']}\\system32\\expand.exe -f:* msu_file destination")
+ expect(provider).to receive(:shell_out!).with("#{ENV['SYSTEMROOT']}\\system32\\expand.exe -f:* msu_file destination")
provider.extract_msu_contents("msu_file", "destination")
end
end
diff --git a/spec/unit/provider/package/openbsd_spec.rb b/spec/unit/provider/package/openbsd_spec.rb
index 20eb85dfcf..01d6571f65 100644
--- a/spec/unit/provider/package/openbsd_spec.rb
+++ b/spec/unit/provider/package/openbsd_spec.rb
@@ -45,19 +45,19 @@ describe Chef::Provider::Package::Openbsd do
context "when not already installed" do
before do
- allow(provider).to receive(:shell_out!).with("pkg_info", "-e", "#{name}->0", anything()).and_return(instance_double("shellout", :stdout => ""))
+ allow(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{name}->0", anything()).and_return(instance_double("shellout", stdout: ""))
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(
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}\n"))
+ expect(provider).to receive(:shell_out_compacted!).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
@@ -69,8 +69,8 @@ describe Chef::Provider::Package::Openbsd do
context "if no version is specified" do
it "should raise an exception" do
- expect(provider).to receive(:shell_out!).with("pkg_info", "-I", name, anything()).and_return(
- instance_double("shellout", :stdout => "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n"))
expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /multiple matching candidates/)
end
end
@@ -83,13 +83,13 @@ describe Chef::Provider::Package::Openbsd do
context "if no version is specified" do
it "should run the installation command" do
- expect(provider).to receive(:shell_out!).with("pkg_info", "-e", "#{package_name}->0", anything()).and_return(instance_double("shellout", :stdout => ""))
- expect(provider).to receive(:shell_out!).with("pkg_info", "-I", name, anything()).and_return(
- instance_double("shellout", :stdout => "#{name}-#{version}-#{flavor}\n"))
- expect(provider).to receive(:shell_out!).with(
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{package_name}->0", anything()).and_return(instance_double("shellout", stdout: ""))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything()).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor}\n"))
+ expect(provider).to receive(:shell_out_compacted!).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 }
+ ) { OpenStruct.new status: true }
provider.run_action(:install)
end
end
@@ -98,14 +98,14 @@ describe Chef::Provider::Package::Openbsd do
context "if a version is specified" do
it "should use the flavor from the version" do
- expect(provider).to receive(:shell_out!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything()).and_return(
- instance_double("shellout", :stdout => "#{name}-#{version}-#{flavor_a}\n"))
+ expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything()).and_return(
+ instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n"))
new_resource.version("#{version}-#{flavor_b}")
- expect(provider).to receive(:shell_out!).with(
+ expect(provider).to receive(:shell_out_compacted!).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 }
+ ) { OpenStruct.new status: true }
provider.run_action(:install)
end
end
@@ -122,9 +122,9 @@ describe Chef::Provider::Package::Openbsd do
@provider.current_resource = @current_resource
end
it "should run the command to delete the installed package" do
- expect(@provider).to receive(:shell_out!).with(
+ expect(@provider).to receive(:shell_out_compacted!).with(
"pkg_delete", @name, env: nil, timeout: 900
- ) { OpenStruct.new :status => true }
+ ) { OpenStruct.new status: true }
@provider.remove_package(@name, nil)
end
end
diff --git a/spec/unit/provider/package/pacman_spec.rb b/spec/unit/provider/package/pacman_spec.rb
index ceae73dbd1..10bb3492b2 100644
--- a/spec/unit/provider/package/pacman_spec.rb
+++ b/spec/unit/provider/package/pacman_spec.rb
@@ -26,14 +26,14 @@ describe Chef::Provider::Package::Pacman do
@new_resource = Chef::Resource::Package.new("nano")
@current_resource = Chef::Resource::Package.new("nano")
- @status = double(:stdout => "", :exitstatus => 0)
+ @status = double(stdout: "", exitstatus: 0)
@provider = Chef::Provider::Package::Pacman.new(@new_resource, @run_context)
allow(Chef::Resource::Package).to receive(:new).and_return(@current_resource)
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@stdin = StringIO.new
- @stdout = StringIO.new(<<-ERR)
-error: package "nano" not found
+ @stdout = StringIO.new(<<~ERR)
+ error: package "nano" not found
ERR
@stderr = StringIO.new
@pid = 2342
@@ -51,79 +51,79 @@ 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_compacted).with("pacman", "-Qi", @new_resource.package_name, { timeout: 900 }).and_return(@status)
@provider.load_current_resource
end
it "should read stdout on pacman" do
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@provider.load_current_resource
end
it "should set the installed version to nil on the current resource if pacman installed version not exists" do
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@provider.load_current_resource
end
it "should set the installed version if pacman has one" do
- stdout = <<-PACMAN
-Name : nano
-Version : 2.2.2-1
-URL : http://www.nano-editor.org
-Licenses : GPL
-Groups : base
-Provides : None
-Depends On : glibc ncurses
-Optional Deps : None
-Required By : None
-Conflicts With : None
-Replaces : None
-Installed Size : 1496.00 K
-Packager : Andreas Radke <andyrtr@archlinux.org>
-Architecture : i686
-Build Date : Mon 18 Jan 2010 06:16:16 PM CET
-Install Date : Mon 01 Feb 2010 10:06:30 PM CET
-Install Reason : Explicitly installed
-Install Script : Yes
-Description : Pico editor clone with enhancements
+ stdout = <<~PACMAN
+ Name : nano
+ Version : 2.2.2-1
+ URL : http://www.nano-editor.org
+ Licenses : GPL
+ Groups : base
+ Provides : None
+ Depends On : glibc ncurses
+ Optional Deps : None
+ Required By : None
+ Conflicts With : None
+ Replaces : None
+ Installed Size : 1496.00 K
+ Packager : Andreas Radke <andyrtr@archlinux.org>
+ Architecture : i686
+ Build Date : Mon 18 Jan 2010 06:16:16 PM CET
+ Install Date : Mon 01 Feb 2010 10:06:30 PM CET
+ Install Reason : Explicitly installed
+ Install Script : Yes
+ Description : Pico editor clone with enhancements
PACMAN
- status = double(:stdout => stdout, :exitstatus => 0)
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: stdout, exitstatus: 0)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
@provider.load_current_resource
expect(@current_resource.version).to eq("2.2.2-1")
end
it "should set the candidate version if pacman has one" do
- status = double(:stdout => "core nano 2.2.3-1", :exitstatus => 0)
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "core nano 2.2.3-1", exitstatus: 0)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
@provider.load_current_resource
expect(@provider.candidate_version).to eql("2.2.3-1")
end
it "should use pacman.conf to determine valid repo names for package versions" do
- @pacman_conf = <<-PACMAN_CONF
-[options]
-HoldPkg = pacman glibc
-Architecture = auto
+ @pacman_conf = <<~PACMAN_CONF
+ [options]
+ HoldPkg = pacman glibc
+ Architecture = auto
-[customrepo]
-Server = https://my.custom.repo
+ [customrepo]
+ Server = https://my.custom.repo
-[core]
-Include = /etc/pacman.d/mirrorlist
+ [core]
+ Include = /etc/pacman.d/mirrorlist
-[extra]
-Include = /etc/pacman.d/mirrorlist
+ [extra]
+ Include = /etc/pacman.d/mirrorlist
-[community]
-Include = /etc/pacman.d/mirrorlist
+ [community]
+ Include = /etc/pacman.d/mirrorlist
PACMAN_CONF
- status = double(:stdout => "customrepo nano 1.2.3-4", :exitstatus => 0)
+ status = double(stdout: "customrepo nano 1.2.3-4", exitstatus: 0)
allow(::File).to receive(:exist?).with("/etc/pacman.conf").and_return(true)
allow(::File).to receive(:read).with("/etc/pacman.conf").and_return(@pacman_conf)
- allow(@provider).to receive(:shell_out).and_return(status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
@provider.load_current_resource
expect(@provider.candidate_version).to eql("1.2.3-4")
@@ -140,7 +140,7 @@ PACMAN_CONF
end
it "should raise an exception if pacman does not return a candidate version" do
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package)
end
@@ -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_compacted!).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_compacted!).with("pacman", "--sync", "--noconfirm", "--noprogressbar", "--debug", "nano", { timeout: 900 })
@new_resource.options("--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_compacted!).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_compacted!).with("pacman", "--remove", "--noconfirm", "--noprogressbar", "--debug", "nano", { timeout: 900 })
@new_resource.options("--debug")
@provider.remove_package("nano", "1.0")
diff --git a/spec/unit/provider/package/paludis_spec.rb b/spec/unit/provider/package/paludis_spec.rb
index df0150c8c0..10c0d0f7e8 100644
--- a/spec/unit/provider/package/paludis_spec.rb
+++ b/spec/unit/provider/package/paludis_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Vasiliy Tolstov <v.tolstov@selfip.ru>
-# Copyright:: Copyright 2014-2016, Chef Software Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,84 +33,84 @@ describe Chef::Provider::Package::Paludis do
@stdin = StringIO.new
@stderr = StringIO.new
- @stdout = <<-PKG_STATUS
-group/ntp 0 accounts
-group/ntp 0 installed-accounts
-net/ntp 4.2.6_p5-r2 arbor
-user/ntp 0 accounts
-user/ntp 0 installed-accounts
-net/ntp 4.2.6_p5-r1 installed
+ @stdout = <<~PKG_STATUS
+ group/ntp 0 accounts
+ group/ntp 0 installed-accounts
+ net/ntp 4.2.6_p5-r2 arbor
+ user/ntp 0 accounts
+ 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
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(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
expect(Chef::Resource::Package).to receive(:new).and_return(@current_resource)
@provider.load_current_resource
end
it "should set the current resources package name to the new resources package name" do
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
expect(@current_resource).to receive(:package_name).with(@new_resource.package_name)
@provider.load_current_resource
end
it "should run pkg info with the package name" do
- expect(@provider).to receive(:shell_out!).with("cave", "-L", "warning", "print-ids", "-M", "none", "-m", @new_resource.package_name, "-f", "%c/%p %v %r\n").and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "print-ids", "-M", "none", "-m", @new_resource.package_name, "-f", "%c/%p %v %r\n", timeout: 900).and_return(@shell_out)
@provider.load_current_resource
end
it "should return new version if package is installed" do
- @stdout.replace(<<-INSTALLED)
-group/ntp 0 accounts
-group/ntp 0 installed-accounts
-net/ntp 4.2.6_p5-r2 arbor
-user/ntp 0 accounts
-user/ntp 0 installed-accounts
-net/ntp 4.2.6_p5-r1 installed
+ @stdout.replace(<<~INSTALLED)
+ group/ntp 0 accounts
+ group/ntp 0 installed-accounts
+ net/ntp 4.2.6_p5-r2 arbor
+ user/ntp 0 accounts
+ user/ntp 0 installed-accounts
+ net/ntp 4.2.6_p5-r1 installed
INSTALLED
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
@provider.load_current_resource
expect(@current_resource.version).to eq("4.2.6_p5-r1")
expect(@provider.candidate_version).to eql("4.2.6_p5-r2")
end
it "should return the current resource" do
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
expect(@provider.load_current_resource).to eql(@current_resource)
end
end
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 || 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "resolve", "-x", "=net/ntp-4.2.6_p5-r2", { timeout: @new_resource.timeout || 900 })
@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 || 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "resolve", "-x", "--preserve-world", "=net/ntp-4.2.6_p5-r2", { timeout: @new_resource.timeout || 900 })
@new_resource.options "--preserve-world"
@provider.install_package("net/ntp", "4.2.6_p5-r2")
end
it "should not contain invalid characters for the version string" do
- @stdout.replace(<<-PKG_STATUS)
-sys-process/lsof 4.87 arbor
-sys-process/lsof 4.87 x86_64
+ @stdout.replace(<<~PKG_STATUS)
+ 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 || 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "resolve", "-x", "=sys-process/lsof-4.87", { timeout: @new_resource.timeout || 900 })
@provider.install_package("sys-process/lsof", "4.87")
end
it "should not include the human-readable version in the candidate_version" do
- @stdout.replace(<<-PKG_STATUS)
-sys-process/lsof 4.87 arbor
-sys-process/lsof 4.87 x86_64
+ @stdout.replace(<<~PKG_STATUS)
+ sys-process/lsof 4.87 arbor
+ sys-process/lsof 4.87 x86_64
PKG_STATUS
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
@provider.load_current_resource
expect(@current_resource.version).to be_nil
expect(@provider.candidate_version).to eql("4.87")
@@ -119,14 +119,14 @@ 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 || 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "resolve", "-x", "=net/ntp-4.2.6_p5-r2", { timeout: @new_resource.timeout || 900 })
@provider.upgrade_package("net/ntp", "4.2.6_p5-r2")
end
end
context "when uninstalling a package" do
it "should run pkg uninstall with the package name and version" do
- expect(@provider).to receive(:shell_out!).with("cave", "-L", "warning", "uninstall", "-x", "=net/ntp-4.2.6_p5-r2")
+ expect(@provider).to receive(:shell_out_compacted!).with("cave", "-L", "warning", "uninstall", "-x", "=net/ntp-4.2.6_p5-r2", timeout: 900)
@provider.remove_package("net/ntp", "4.2.6_p5-r2")
end
diff --git a/spec/unit/provider/package/portage_spec.rb b/spec/unit/provider/package/portage_spec.rb
index d77e180181..e1036bea74 100644
--- a/spec/unit/provider/package/portage_spec.rb
+++ b/spec/unit/provider/package/portage_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Caleb Tennis (<caleb.tennis@gmail.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,19 +22,19 @@ describe Chef::Provider::Package::Portage, "load_current_resource" do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
- @new_resource = Chef::Resource::Package.new("dev-util/git")
- @new_resource_without_category = Chef::Resource::Package.new("git")
- @current_resource = Chef::Resource::Package.new("dev-util/git")
+ @new_resource = Chef::Resource::PortagePackage.new("dev-util/git")
+ @new_resource_without_category = Chef::Resource::PortagePackage.new("git")
+ @current_resource = Chef::Resource::PortagePackage.new("dev-util/git")
@provider = Chef::Provider::Package::Portage.new(@new_resource, @run_context)
- allow(Chef::Resource::Package).to receive(:new).and_return(@current_resource)
+ allow(Chef::Resource::PortagePackage).to receive(:new).and_return(@current_resource)
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)
+ expect(Chef::Resource::PortagePackage).to receive(:new).and_return(@current_resource)
@provider.load_current_resource
end
@@ -108,193 +108,57 @@ describe Chef::Provider::Package::Portage, "load_current_resource" 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"
- expect(@provider).not_to receive(:shell_out)
+ expect(@provider).not_to receive(:shell_out_compacted)
@provider.candidate_version
end
it "should throw an exception if the exitstatus is not 0" do
- status = double(:stdout => "", :exitstatus => 1)
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "", stderr: "", exitstatus: 1)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package)
end
it "should find the candidate_version if a category is specifed and there are no duplicates" do
- output = <<EOF
-Searching...
-[ Results for search key : git ]
-[ Applications found : 14 ]
-
-* app-misc/digitemp [ Masked ]
- Latest version available: 3.5.0
- Latest version installed: [ Not Installed ]
- Size of files: 261 kB
- Homepage: http://www.digitemp.com/ http://www.ibutton.com/
- Description: Temperature logging and reporting using Dallas Semiconductor's iButtons and 1-Wire protocol
- License: GPL-2
-
-* dev-util/git
- Latest version available: 1.6.0.6
- Latest version installed: ignore
- Size of files: 2,725 kB
- Homepage: http://git.or.cz/
- Description: GIT - the stupid content tracker, the revision control system heavily used by the Linux kernel team
- License: GPL-2
-
-* dev-util/gitosis [ Masked ]
- Latest version available: 0.2_p20080825
- Latest version installed: [ Not Installed ]
- Size of files: 31 kB
- Homepage: http://eagain.net/gitweb/?p=gitosis.git;a=summary
- Description: gitosis -- software for hosting git repositories
- License: GPL-2
-EOF
-
- status = double(:stdout => output, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).and_return(status)
- expect(@provider.candidate_version).to eq("1.6.0.6")
+ status = double(stdout: "dev-vcs/git-2.16.2", exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
+ expect(@provider.candidate_version).to eq("2.16.2")
end
it "should find the candidate_version if a category is not specifed and there are no duplicates" do
- output = <<EOF
-Searching...
-[ Results for search key : git ]
-[ Applications found : 14 ]
-
-* app-misc/digitemp [ Masked ]
- Latest version available: 3.5.0
- Latest version installed: [ Not Installed ]
- Size of files: 261 kB
- Homepage: http://www.digitemp.com/ http://www.ibutton.com/
- Description: Temperature logging and reporting using Dallas Semiconductor's iButtons and 1-Wire protocol
- License: GPL-2
-
-* dev-util/git
- Latest version available: 1.6.0.6
- Latest version installed: ignore
- Size of files: 2,725 kB
- Homepage: http://git.or.cz/
- Description: GIT - the stupid content tracker, the revision control system heavily used by the Linux kernel team
- License: GPL-2
-
-* dev-util/gitosis [ Masked ]
- Latest version available: 0.2_p20080825
- Latest version installed: [ Not Installed ]
- Size of files: 31 kB
- Homepage: http://eagain.net/gitweb/?p=gitosis.git;a=summary
- Description: gitosis -- software for hosting git repositories
- License: GPL-2
-EOF
-
- status = double(:stdout => output, :exitstatus => 0)
+ status = double(stdout: "dev-vcs/git-2.16.2", exitstatus: 0)
@provider = Chef::Provider::Package::Portage.new(@new_resource_without_category, @run_context)
- expect(@provider).to receive(:shell_out).and_return(status)
- expect(@provider.candidate_version).to eq("1.6.0.6")
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
+ expect(@provider.candidate_version).to eq("2.16.2")
end
it "should throw an exception if a category is not specified and there are duplicates" do
- output = <<EOF
-Searching...
-[ Results for search key : git ]
-[ Applications found : 14 ]
-
-* app-misc/digitemp [ Masked ]
- Latest version available: 3.5.0
- Latest version installed: [ Not Installed ]
- Size of files: 261 kB
- Homepage: http://www.digitemp.com/ http://www.ibutton.com/
- Description: Temperature logging and reporting using Dallas Semiconductor's iButtons and 1-Wire protocol
- License: GPL-2
+ stderr_output = <<~EOF
+ You specified an unqualified atom that matched multiple packages:
+ * app-misc/sphinx
+ * dev-python/sphinx
-* app-misc/git
- Latest version available: 4.3.20
- Latest version installed: [ Not Installed ]
- Size of files: 416 kB
- Homepage: http://www.gnu.org/software/git/
- Description: GNU Interactive Tools - increase speed and efficiency of most daily task
- License: GPL-2
-
-* dev-util/git
- Latest version available: 1.6.0.6
- Latest version installed: ignore
- Size of files: 2,725 kB
- Homepage: http://git.or.cz/
- Description: GIT - the stupid content tracker, the revision control system heavily used by the Linux kernel team
- License: GPL-2
-
-* dev-util/gitosis [ Masked ]
- Latest version available: 0.2_p20080825
- Latest version installed: [ Not Installed ]
- Size of files: 31 kB
- Homepage: http://eagain.net/gitweb/?p=gitosis.git;a=summary
- Description: gitosis -- software for hosting git repositories
- License: GPL-2
+ Please use a more specific atom.
EOF
-
- status = double(:stdout => output, :exitstatus => 0)
+ status = double(stdout: "", stderr: stderr_output, exitstatus: 1)
@provider = Chef::Provider::Package::Portage.new(@new_resource_without_category, @run_context)
- expect(@provider).to receive(:shell_out).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package)
end
-
- it "should find the candidate_version if a category is specifed and there are category duplicates" do
- output = <<EOF
-Searching...
-[ Results for search key : git ]
-[ Applications found : 14 ]
-
-* app-misc/digitemp [ Masked ]
- Latest version available: 3.5.0
- Latest version installed: [ Not Installed ]
- Size of files: 261 kB
- Homepage: http://www.digitemp.com/ http://www.ibutton.com/
- Description: Temperature logging and reporting using Dallas Semiconductor's iButtons and 1-Wire protocol
- License: GPL-2
-
-* app-misc/git
- Latest version available: 4.3.20
- Latest version installed: [ Not Installed ]
- Size of files: 416 kB
- Homepage: http://www.gnu.org/software/git/
- Description: GNU Interactive Tools - increase speed and efficiency of most daily task
- License: GPL-2
-
-* dev-util/git
- Latest version available: 1.6.0.6
- Latest version installed: ignore
- Size of files: 2,725 kB
- Homepage: http://git.or.cz/
- Description: GIT - the stupid content tracker, the revision control system heavily used by the Linux kernel team
- License: GPL-2
-
-* dev-util/gitosis [ Masked ]
- Latest version available: 0.2_p20080825
- Latest version installed: [ Not Installed ]
- Size of files: 31 kB
- Homepage: http://eagain.net/gitweb/?p=gitosis.git;a=summary
- Description: gitosis -- software for hosting git repositories
- License: GPL-2
-EOF
-
- status = double(:stdout => output, :exitstatus => 0)
- @provider = Chef::Provider::Package::Portage.new(@new_resource, @run_context)
- expect(@provider).to receive(:shell_out).and_return(status)
- expect(@provider.candidate_version).to eq("1.6.0.6")
- end
end
describe Chef::Provider::Package::Portage, "install_package" do
it "should install a normally versioned package using portage" do
- expect(@provider).to receive(:shell_out!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "=dev-util/git-1.0.0")
+ expect(@provider).to receive(:shell_out_compacted!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "=dev-util/git-1.0.0", timeout: 3600)
@provider.install_package("dev-util/git", "1.0.0")
end
it "should install a tilde versioned package using portage" do
- expect(@provider).to receive(:shell_out!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "~dev-util/git-1.0.0")
+ expect(@provider).to receive(:shell_out_compacted!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "~dev-util/git-1.0.0", timeout: 3600)
@provider.install_package("dev-util/git", "~1.0.0")
end
it "should add options to the emerge command when specified" do
- expect(@provider).to receive(:shell_out!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "--oneshot", "=dev-util/git-1.0.0")
+ expect(@provider).to receive(:shell_out_compacted!).with("emerge", "-g", "--color", "n", "--nospinner", "--quiet", "--oneshot", "=dev-util/git-1.0.0", timeout: 3600)
@new_resource.options "--oneshot"
@provider.install_package("dev-util/git", "1.0.0")
end
@@ -302,12 +166,12 @@ EOF
describe Chef::Provider::Package::Portage, "remove_package" do
it "should un-emerge the package with no version specified" do
- expect(@provider).to receive(:shell_out!).with("emerge", "--unmerge", "--color", "n", "--nospinner", "--quiet", "dev-util/git")
+ expect(@provider).to receive(:shell_out_compacted!).with("emerge", "--unmerge", "--color", "n", "--nospinner", "--quiet", "dev-util/git", timeout: 3600)
@provider.remove_package("dev-util/git", nil)
end
it "should un-emerge the package with a version specified" do
- expect(@provider).to receive(:shell_out!).with("emerge", "--unmerge", "--color", "n", "--nospinner", "--quiet", "=dev-util/git-1.0.0")
+ expect(@provider).to receive(:shell_out_compacted!).with("emerge", "--unmerge", "--color", "n", "--nospinner", "--quiet", "=dev-util/git-1.0.0", timeout: 3600)
@provider.remove_package("dev-util/git", "1.0.0")
end
end
diff --git a/spec/unit/provider/package/powershell_spec.rb b/spec/unit/provider/package/powershell_spec.rb
index 4ab100f07f..c7a16acaa2 100644
--- a/spec/unit/provider/package/powershell_spec.rb
+++ b/spec/unit/provider/package/powershell_spec.rb
@@ -22,6 +22,7 @@ require "chef/mixin/powershell_out"
describe Chef::Provider::Package::Powershell do
include Chef::Mixin::PowershellOut
let(:timeout) { 900 }
+ let(:source) { nil }
let(:new_resource) { Chef::Resource::PowershellPackage.new("windows_test_pkg") }
@@ -33,65 +34,79 @@ describe Chef::Provider::Package::Powershell do
end
let(:package_xcertificate_installed) do
- double("powershell_out", :stdout => "2.1.0.0\r\n")
+ double("powershell_out", stdout: "2.1.0.0\r\n")
end
let(:package_xcertificate_installed_2_0_0_0) do
- double("powershell_out", :stdout => "2.0.0.0\r\n")
+ double("powershell_out", stdout: "2.0.0.0\r\n")
end
let(:package_xcertificate_available) do
- double("powershell_out", :stdout => "2.1.0.0\r\n")
+ double("powershell_out", stdout: "2.1.0.0\r\n")
end
let(:package_xcertificate_available_2_0_0_0) do
- double("powershell_out", :stdout => "2.0.0.0\r\n")
+ double("powershell_out", stdout: "2.0.0.0\r\n")
end
let(:package_xcertificate_not_installed) do
- double("powershell_out", :stdout => "")
+ double("powershell_out", stdout: "")
end
let(:package_xcertificate_not_available) do
- double("powershell_out", :stdout => "")
+ double("powershell_out", stdout: "")
end
let(:package_xnetworking_installed) do
- double("powershell_out", :stdout => "2.12.0.0\r\n")
+ double("powershell_out", stdout: "2.12.0.0\r\n")
end
let(:package_xnetworking_installed_2_11_0_0) do
- double("powershell_out", :stdout => "2.11.0.0\r\n")
+ double("powershell_out", stdout: "2.11.0.0\r\n")
end
let(:package_xnetworking_available) do
- double("powershell_out", :stdout => "2.12.0.0\r\n")
+ double("powershell_out", stdout: "2.12.0.0\r\n")
end
let(:package_xnetworking_available_2_11_0_0) do
- double("powershell_out", :stdout => "2.11.0.0\r\n")
+ double("powershell_out", stdout: "2.11.0.0\r\n")
end
let(:package_xnetworking_not_installed) do
- double("powershell_out", :stdout => "")
+ double("powershell_out", stdout: "")
end
let(:package_xnetworking_not_available) do
- double("powershell_out", :stdout => "")
+ double("powershell_out", stdout: "")
end
let(:package_7zip_available) do
- double("powershell_out", :stdout => "16.02\r\n")
+ double("powershell_out", stdout: "16.02\r\n")
end
let(:package_7zip_not_installed) do
- double("powershell_out", :stdout => "")
+ double("powershell_out", stdout: "")
end
let(:powershell_installed_version) do
- double("powershell_out", :stdout => "5")
+ double("powershell_out", stdout: "5")
end
+ let(:generated_command) { "( Get-Package posh-git -Force -ForceBootstrap ).Version" }
+ let(:generated_get_cmdlet) { "( Get-Package xNetworking -Force -ForceBootstrap ).Version" }
+ let(:generated_get_cmdlet_with_version) { "( Get-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 ).Version" }
+ let(:generated_find_cmdlet) { "( Find-Package xNetworking -Force -ForceBootstrap ).Version" }
+ let(:generated_find_cmdlet_with_version) { "( Find-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 ).Version" }
+ let(:generated_find_cmdlet_with_source) { "( Find-Package xNetworking -Force -ForceBootstrap -Source MyGallery ).Version" }
+ let(:generated_find_cmdlet_with_source_and_version) { "( Find-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 -Source MyGallery ).Version" }
+ let(:generated_install_cmdlet) { "( Install-Package xNetworking -Force -ForceBootstrap ).Version" }
+ let(:generated_install_cmdlet_with_version) { "( Install-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 ).Version" }
+ let(:generated_install_cmdlet_with_source) { "( Install-Package xNetworking -Force -ForceBootstrap -Source MyGallery ).Version" }
+ let(:generated_install_cmdlet_with_source_and_version) { "( Install-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 -Source MyGallery ).Version" }
+ let(:generated_uninstall_cmdlet) { "( Uninstall-Package xNetworking -Force -ForceBootstrap ).Version" }
+ let(:generated_uninstall_cmdlet_with_version) { "( Uninstall-Package xNetworking -Force -ForceBootstrap -RequiredVersion 1.0.0.0 ).Version" }
+
describe "#initialize" do
it "should return the correct class" do
expect(provider).to be_kind_of(Chef::Provider::Package::Powershell)
@@ -101,67 +116,75 @@ describe Chef::Provider::Package::Powershell do
describe "#candidate_version" do
it "should set the candidate_version to the latest version when not pinning" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
+ new_resource.package_name(["xNetworking"])
+ new_resource.version(nil)
+ expect(provider.candidate_version).to eql(["2.12.0.0"])
+ end
+
+ it "should use the candidate_version from the correct source" do
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap -Source MyGallery ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
new_resource.package_name(["xNetworking"])
new_resource.version(nil)
+ new_resource.source("MyGallery")
expect(provider.candidate_version).to eql(["2.12.0.0"])
end
it "should set the candidate_version to the latest version when not pinning and package name is space seperated" do
- allow(provider).to receive(:powershell_out).with("(Find-Package '7-Zip 16.02 (x64)' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_7zip_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package '7-Zip 16.02 (x64)' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_7zip_available)
new_resource.package_name(["7-Zip 16.02 (x64)"])
new_resource.version(nil)
expect(provider.candidate_version).to eql(["16.02"])
end
it "should set the candidate_version to pinned version if available" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -RequiredVersion 2.0.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available_2_0_0_0)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.0.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available_2_0_0_0)
new_resource.package_name(["xCertificate"])
new_resource.version(["2.0.0.0"])
expect(provider.candidate_version).to eql(["2.0.0.0"])
end
it "should set the candidate_version to nil if there is no candidate" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
new_resource.package_name(["xCertificate"])
expect(provider.candidate_version).to eql([nil])
end
it "should set the candidate_version correctly when there are two packages to install" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(nil)
expect(provider.candidate_version).to eql(["2.1.0.0", "2.12.0.0"])
end
it "should set the candidate_version correctly when only the first is installable" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(nil)
expect(provider.candidate_version).to eql(["2.1.0.0", nil])
end
it "should set the candidate_version correctly when only the last is installable" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(nil)
expect(provider.candidate_version).to eql([nil, "2.12.0.0"])
end
it "should set the candidate_version correctly when neither are is installable and version is passed as nil array" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
new_resource.package_name(%w{xNetworking xCertificate})
new_resource.version([nil, nil])
expect(provider.candidate_version).to eql([nil, nil])
end
it "should set the candidate_version correctly when neither are is installable and version is not passed" do
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
new_resource.package_name(%w{xNetworking xCertificate})
new_resource.version(nil)
expect(provider.candidate_version).to eql([nil, nil])
@@ -169,15 +192,127 @@ describe Chef::Provider::Package::Powershell do
end
+ describe "#build_powershell_package_command" do
+ it "can build a valid command from a single string" do
+ expect(provider.build_powershell_package_command("Get-Package posh-git")).to eql(generated_command)
+ end
+
+ it "can build a valid command from an array" do
+ expect(provider.build_powershell_package_command(["Get-Package", "posh-git"])).to eql(generated_command)
+ end
+
+ context "when source is nil" do
+ it "build get commands correctly" do
+ expect(provider.build_powershell_package_command("Get-Package xNetworking")).to eql(generated_get_cmdlet)
+ end
+
+ it "build get commands correctly when a version is passed" do
+ expect(provider.build_powershell_package_command("Get-Package xNetworking", "1.0.0.0")).to eql(generated_get_cmdlet_with_version)
+ end
+
+ it "builds find commands correctly" do
+ expect(provider.build_powershell_package_command("Find-Package xNetworking")).to eql(generated_find_cmdlet)
+ end
+
+ it "builds find commands correctly when a version is passed" do
+ expect(provider.build_powershell_package_command("Find-Package xNetworking", "1.0.0.0")).to eql(generated_find_cmdlet_with_version)
+ end
+
+ it "build install commands correctly" do
+ expect(provider.build_powershell_package_command("Install-Package xNetworking")).to eql(generated_install_cmdlet)
+ end
+
+ it "build install commands correctly when a version is passed" do
+ expect(provider.build_powershell_package_command("Install-Package xNetworking", "1.0.0.0")).to eql(generated_install_cmdlet_with_version)
+ end
+
+ it "build install commands correctly" do
+ expect(provider.build_powershell_package_command("Uninstall-Package xNetworking")).to eql(generated_uninstall_cmdlet)
+ end
+
+ it "build install commands correctly when a version is passed" do
+ expect(provider.build_powershell_package_command("Uninstall-Package xNetworking", "1.0.0.0")).to eql(generated_uninstall_cmdlet_with_version)
+ end
+ end
+
+ context "when source is set" do
+ it "build get commands correctly" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Get-Package xNetworking")).to eql(generated_get_cmdlet)
+ end
+
+ it "build get commands correctly when a version is passed" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Get-Package xNetworking", "1.0.0.0")).to eql(generated_get_cmdlet_with_version)
+ end
+
+ it "builds find commands correctly" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Find-Package xNetworking")).to eql(generated_find_cmdlet_with_source)
+ end
+
+ it "builds find commands correctly when a version is passed" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Find-Package xNetworking", "1.0.0.0")).to eql(generated_find_cmdlet_with_source_and_version)
+ end
+
+ it "build install commands correctly" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Install-Package xNetworking")).to eql(generated_install_cmdlet_with_source)
+ end
+
+ it "build install commands correctly when a version is passed" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Install-Package xNetworking", "1.0.0.0")).to eql(generated_install_cmdlet_with_source_and_version)
+ end
+
+ it "build install commands correctly" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Uninstall-Package xNetworking")).to eql(generated_uninstall_cmdlet)
+ end
+
+ it "build install commands correctly when a version is passed" do
+ new_resource.source("MyGallery")
+ expect(provider.build_powershell_package_command("Uninstall-Package xNetworking", "1.0.0.0")).to eql(generated_uninstall_cmdlet_with_version)
+ end
+ end
+ end
+
describe "#action_install" do
it "should install a single package" do
provider.load_current_resource
new_resource.package_name(["xCertificate"])
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
+ provider.run_action(:install)
+ expect(new_resource).to be_updated_by_last_action
+ end
+
+ it "should install a single package from a custom source" do
+ provider.load_current_resource
+ new_resource.package_name(["xCertificate"])
+ new_resource.version(nil)
+ new_resource.source("MyGallery")
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -Source MyGallery ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 -Source MyGallery ).Version", { timeout: new_resource.timeout })
+ provider.run_action(:install)
+ expect(new_resource).to be_updated_by_last_action
+ end
+
+ it "should install a package without the publisher check" do
+ provider.load_current_resource
+ new_resource.package_name(["xCertificate"])
+ new_resource.version(nil)
+ new_resource.skip_publisher_check(true)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap -SkipPublisherCheck ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 -SkipPublisherCheck ).Version", { timeout: new_resource.timeout })
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -186,10 +321,10 @@ describe Chef::Provider::Package::Powershell do
provider.load_current_resource
new_resource.package_name(["7-Zip 16.02 (x64)"])
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package '7-Zip 16.02 (x64)' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_7zip_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name '7-Zip 16.02 (x64)' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_7zip_not_installed)
+ allow(provider).to receive(:powershell_out).with("( Find-Package '7-Zip 16.02 (x64)' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_7zip_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package '7-Zip 16.02 (x64)' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_7zip_not_installed)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package '7-Zip 16.02 (x64)' -Force -ForceBootstrap -RequiredVersion 16.02", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package '7-Zip 16.02 (x64)' -Force -ForceBootstrap -RequiredVersion 16.02 ).Version", { timeout: new_resource.timeout })
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -201,10 +336,10 @@ describe Chef::Provider::Package::Powershell do
provider.load_current_resource
new_resource.package_name(["xCertificate"])
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -213,8 +348,8 @@ describe Chef::Provider::Package::Powershell do
it "should not install packages that are up-to-date" do
new_resource.package_name(["xCertificate"])
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
provider.load_current_resource
expect(provider).not_to receive(:install_package)
@@ -225,8 +360,8 @@ describe Chef::Provider::Package::Powershell do
it "should not install packages that are up-to-date" do
new_resource.package_name(["xNetworking"])
new_resource.version(["2.11.0.0"])
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -RequiredVersion 2.11.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xNetworking' -RequiredVersion 2.11.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available_2_11_0_0)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available_2_11_0_0)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
provider.load_current_resource
expect(provider).not_to receive(:install_package)
@@ -239,13 +374,13 @@ describe Chef::Provider::Package::Powershell do
# new_version.resource[0]
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version([nil, "2.11.0.0"])
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -RequiredVersion 2.11.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available_2_11_0_0)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xNetworking' -RequiredVersion 2.11.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available_2_11_0_0)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
- expect(provider).to receive(:powershell_out).with("Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.11.0.0 ).Version", { timeout: new_resource.timeout })
provider.load_current_resource
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
@@ -254,13 +389,13 @@ describe Chef::Provider::Package::Powershell do
it "should split up commands when given two packages, one with a version pin" do
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(["2.1.0.0", nil])
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
- expect(provider).to receive(:powershell_out).with("Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.12.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.12.0.0 ).Version", { timeout: new_resource.timeout })
provider.load_current_resource
provider.run_action(:install)
@@ -270,13 +405,29 @@ describe Chef::Provider::Package::Powershell do
it "should do multipackage installs when given two packages without constraints" do
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
- expect(provider).to receive(:powershell_out).with("Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
- expect(provider).to receive(:powershell_out).with("Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.12.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.12.0.0 ).Version", { timeout: new_resource.timeout })
+ provider.load_current_resource
+ provider.run_action(:install)
+ expect(new_resource).to be_updated_by_last_action
+ end
+
+ it "should do multipackage installs from a custom source when given two packages without constraints" do
+ new_resource.package_name(%w{xCertificate xNetworking})
+ new_resource.version(nil)
+ new_resource.source("MyGallery")
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -Source MyGallery ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap -Source MyGallery ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 -Source MyGallery ).Version", { timeout: new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Install-Package 'xNetworking' -Force -ForceBootstrap -RequiredVersion 2.12.0.0 -Source MyGallery ).Version", { timeout: new_resource.timeout })
provider.load_current_resource
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
@@ -288,21 +439,34 @@ describe Chef::Provider::Package::Powershell do
provider.load_current_resource
new_resource.package_name(["xCertificate"])
new_resource.version(["2.1.0.0"])
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
expect(provider).not_to receive(:remove_package)
provider.run_action(:remove)
expect(new_resource).not_to be_updated_by_last_action
end
+ it "does not pass the source parameter to get or uninstall cmdlets" do
+ new_resource.package_name(["xCertificate"])
+ new_resource.version(["2.1.0.0"])
+ new_resource.source("MyGallery")
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 -Source MyGallery).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
+ provider.load_current_resource
+ expect(provider).to receive(:powershell_out).with("( Uninstall-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
+ provider.run_action(:remove)
+ expect(new_resource).to be_updated_by_last_action
+ end
+
it "does nothing when all the packages are already removed" do
new_resource.package_name(%w{xCertificate xNetworking})
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xNetworking' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xnetworking_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xNetworking' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xnetworking_not_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
provider.load_current_resource
expect(provider).not_to receive(:remove_package)
@@ -313,11 +477,11 @@ describe Chef::Provider::Package::Powershell do
it "removes a package when version is specified" do
new_resource.package_name(["xCertificate"])
new_resource.version(["2.1.0.0"])
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -RequiredVersion 2.1.0.0 -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
provider.load_current_resource
- expect(provider).to receive(:powershell_out).with("Uninstall-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0", { :timeout => new_resource.timeout })
+ expect(provider).to receive(:powershell_out).with("( Uninstall-Package 'xCertificate' -Force -ForceBootstrap -RequiredVersion 2.1.0.0 ).Version", { timeout: new_resource.timeout })
provider.run_action(:remove)
expect(new_resource).to be_updated_by_last_action
end
@@ -325,11 +489,11 @@ describe Chef::Provider::Package::Powershell do
it "removes a package when version is not specified" do
new_resource.package_name(["xCertificate"])
new_resource.version(nil)
- allow(provider).to receive(:powershell_out).with("(Find-Package 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
- allow(provider).to receive(:powershell_out).with("(Get-Package -Name 'xCertificate' -ForceBootstrap -Force | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Find-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
+ allow(provider).to receive(:powershell_out).with("( Get-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_available)
allow(provider).to receive(:powershell_out).with("$PSVersionTable.PSVersion.Major").and_return(powershell_installed_version)
provider.load_current_resource
- expect(provider).to receive(:powershell_out).with("(Uninstall-Package 'xCertificate' -Force -ForceBootstrap | select version | Format-Table -HideTableHeaders | Out-String).Trim()", { :timeout => new_resource.timeout }).and_return(package_xcertificate_not_available)
+ expect(provider).to receive(:powershell_out).with("( Uninstall-Package 'xCertificate' -Force -ForceBootstrap ).Version", { timeout: new_resource.timeout }).and_return(package_xcertificate_not_available)
provider.run_action(:remove)
expect(new_resource).to be_updated_by_last_action
end
diff --git a/spec/unit/provider/package/rpm_spec.rb b/spec/unit/provider/package/rpm_spec.rb
index 3730878026..3682043dcd 100644
--- a/spec/unit/provider/package/rpm_spec.rb
+++ b/spec/unit/provider/package/rpm_spec.rb
@@ -44,8 +44,8 @@ describe Chef::Provider::Package::Rpm do
allow(::File).to receive(:exist?).with("PLEASE STUB File.exists? EXACTLY").and_return(true)
# Ensure all shell out usage is stubbed with exact arguments
- allow(provider).to receive(:shell_out!).with("PLEASE STUB YOUR SHELLOUT CALLS").and_return(nil)
- allow(provider).to receive(:shell_out).with("PLEASE STUB YOUR SHELLOUT CALLS").and_return(nil)
+ allow(provider).to receive(:shell_out_compacted!).with("PLEASE STUB YOUR SHELLOUT CALLS").and_return(nil)
+ allow(provider).to receive(:shell_out_compacted).with("PLEASE STUB YOUR SHELLOUT CALLS").and_return(nil)
end
describe "when the package source is not valid" do
@@ -85,13 +85,13 @@ describe Chef::Provider::Package::Rpm do
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).
- and_return(rpm_qp_status)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with("rpm", "-qp", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\n", package_source, timeout: 900)
+ .and_return(rpm_qp_status)
- expect(provider).to receive(:shell_out).
- with("rpm", "-q", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\n", package_name, timeout: 900).
- and_return(rpm_q_status)
+ expect(provider).to receive(:shell_out_compacted)
+ .with("rpm", "-q", "--queryformat", "%{NAME} %{VERSION}-%{RELEASE}\n", package_name, timeout: 900)
+ .and_return(rpm_q_status)
end
context "when rpm fails when querying package installed state" do
@@ -151,7 +151,7 @@ describe Chef::Provider::Package::Rpm 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)
+ expect(provider).to_not receive(:shell_out_compacted!).with("rpm", "-i", "/tmp/imagemagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_install
end
@@ -162,7 +162,7 @@ describe Chef::Provider::Package::Rpm 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
- expect(provider).to receive(:shell_out!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_install
end
end
@@ -178,7 +178,7 @@ describe Chef::Provider::Package::Rpm do
let(:rpm_q_stdout) { "imagemagick-c++ 21.4-19.el6_5" }
it "should run rpm -u --oldpackage with the package source to downgrade" 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)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-U", "--oldpackage", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_install
end
@@ -192,7 +192,7 @@ describe Chef::Provider::Package::Rpm 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)
+ expect(provider).to_not receive(:shell_out_compacted!).with("rpm", "-i", "/tmp/imagemagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_upgrade
end
@@ -203,7 +203,7 @@ describe Chef::Provider::Package::Rpm 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
- expect(provider).to receive(:shell_out!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_upgrade
end
end
@@ -219,7 +219,7 @@ describe Chef::Provider::Package::Rpm do
let(:rpm_q_stdout) { "imagemagick-c++ 21.4-19.el6_5" }
it "should run rpm -u --oldpackage with the package source to downgrade" 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)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-U", "--oldpackage", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.action_upgrade
end
@@ -231,7 +231,7 @@ describe Chef::Provider::Package::Rpm do
let(:action) { :remove }
it "should remove the package" do
- expect(provider).to receive(:shell_out!).with("rpm", "-e", "ImageMagick-c++-6.5.4.7-7.el6_5", timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-e", "ImageMagick-c++-6.5.4.7-7.el6_5", timeout: 900)
provider.action_remove
end
end
@@ -357,7 +357,7 @@ describe Chef::Provider::Package::Rpm do
describe "action install" do
it "installs the package" do
- expect(provider).to receive(:shell_out!).with("rpm", "-i", package_source, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-i", package_source, timeout: 900)
provider.action_install
end
@@ -365,7 +365,7 @@ describe Chef::Provider::Package::Rpm do
context "when custom resource options are given" do
it "installs with custom options specified in the resource" do
new_resource.options("--dbpath /var/lib/rpm")
- expect(provider).to receive(:shell_out!).with("rpm", "--dbpath", "/var/lib/rpm", "-i", package_source, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "--dbpath", "/var/lib/rpm", "-i", package_source, timeout: 900)
provider.action_install
end
end
@@ -376,7 +376,7 @@ describe Chef::Provider::Package::Rpm do
let(:action) { :upgrade }
it "installs the package" do
- expect(provider).to receive(:shell_out!).with("rpm", "-i", package_source, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-i", package_source, timeout: 900)
provider.action_upgrade
end
@@ -387,7 +387,7 @@ describe Chef::Provider::Package::Rpm do
let(:action) { :remove }
it "should do nothing" do
- expect(provider).to_not receive(:shell_out!).with("rpm", "-e", "ImageMagick-c++-6.5.4.7-7.el6_5", timeout: 900)
+ expect(provider).to_not receive(:shell_out_compacted!).with("rpm", "-e", "ImageMagick-c++-6.5.4.7-7.el6_5", timeout: 900)
provider.action_remove
end
end
@@ -413,7 +413,7 @@ describe Chef::Provider::Package::Rpm do
it "should install from a path when the package is a path and the source is nil" do
expect(new_resource.source).to eq("/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm")
provider.current_resource = current_resource
- expect(provider).to receive(:shell_out!).with("rpm", "-i", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-i", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
provider.install_package("/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", "6.5.4.7-7.el6_5")
end
@@ -421,7 +421,7 @@ describe Chef::Provider::Package::Rpm do
expect(new_resource.source).to eq("/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm")
current_resource.version("21.4-19.el5")
provider.current_resource = current_resource
- expect(provider).to receive(:shell_out!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("rpm", "-U", "/tmp/ImageMagick-c++-6.5.4.7-7.el6_5.x86_64.rpm", timeout: 900)
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
diff --git a/spec/unit/provider/package/rubygems_spec.rb b/spec/unit/provider/package/rubygems_spec.rb
index 856f8d460c..6b33ab97f9 100644
--- a/spec/unit/provider/package/rubygems_spec.rb
+++ b/spec/unit/provider/package/rubygems_spec.rb
@@ -33,8 +33,10 @@ require "ostruct"
describe Chef::Provider::Package::Rubygems::CurrentGemEnvironment do
include GemspecBackcompatCreator
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
before do
@gem_env = Chef::Provider::Package::Rubygems::CurrentGemEnvironment.new
+ allow(@gem_env).to receive(:logger).and_return(logger)
end
it "determines the gem paths from the in memory rubygems" do
@@ -43,7 +45,10 @@ describe Chef::Provider::Package::Rubygems::CurrentGemEnvironment do
it "determines the installed versions of gems from Gem.source_index" do
gems = [gemspec("rspec-core", Gem::Version.new("1.2.9")), gemspec("rspec-core", Gem::Version.new("1.3.0"))]
- if Gem::Version.new(Gem::VERSION) >= Gem::Version.new("1.8.0")
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new("2.7")
+ expect(Gem::Specification).to receive(:dirs).and_return(["/path/to/gems/specifications", "/another/path/to/gems/specifications"])
+ expect(Gem::Specification).to receive(:installed_stubs).with(["/path/to/gems/specifications", "/another/path/to/gems/specifications"], "rspec-core-*.gemspec").and_return(gems)
+ elsif Gem::Version.new(Gem::VERSION) >= Gem::Version.new("1.8.0")
expect(Gem::Specification).to receive(:find_all_by_name).with("rspec-core", Gem::Dependency.new("rspec-core").requirement).and_return(gems)
else
expect(Gem.source_index).to receive(:search).with(Gem::Dependency.new("rspec-core", nil)).and_return(gems)
@@ -185,21 +190,21 @@ describe Chef::Provider::Package::Rubygems::AlternateGemEnvironment do
it "determines the gem paths from shelling out to gem env" do
gem_env_output = ["/path/to/gems", "/another/path/to/gems"].join(File::PATH_SEPARATOR)
shell_out_result = OpenStruct.new(stdout: gem_env_output)
- expect(@gem_env).to receive(:shell_out!).with("/usr/weird/bin/gem env gempath").and_return(shell_out_result)
+ expect(@gem_env).to receive(:shell_out_compacted!).with("/usr/weird/bin/gem env gempath").and_return(shell_out_result)
expect(@gem_env.gem_paths).to eq(["/path/to/gems", "/another/path/to/gems"])
end
it "caches the gempaths by gem_binary" do
gem_env_output = ["/path/to/gems", "/another/path/to/gems"].join(File::PATH_SEPARATOR)
shell_out_result = OpenStruct.new(stdout: gem_env_output)
- expect(@gem_env).to receive(:shell_out!).with("/usr/weird/bin/gem env gempath").and_return(shell_out_result)
+ expect(@gem_env).to receive(:shell_out_compacted!).with("/usr/weird/bin/gem env gempath").and_return(shell_out_result)
expected = ["/path/to/gems", "/another/path/to/gems"]
expect(@gem_env.gem_paths).to eq(["/path/to/gems", "/another/path/to/gems"])
expect(Chef::Provider::Package::Rubygems::AlternateGemEnvironment.gempath_cache["/usr/weird/bin/gem"]).to eq(expected)
end
it "uses the cached result for gem paths when available" do
- expect(@gem_env).not_to receive(:shell_out!)
+ expect(@gem_env).not_to receive(:shell_out_compacted!)
expected = ["/path/to/gems", "/another/path/to/gems"]
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"])
@@ -219,7 +224,11 @@ describe Chef::Provider::Package::Rubygems::AlternateGemEnvironment do
it "determines the installed versions of gems from the source index" do
gems = [gemspec("rspec", Gem::Version.new("1.2.9")), gemspec("rspec", Gem::Version.new("1.3.0"))]
rspec_dep = Gem::Dependency.new("rspec", nil)
- if Gem::Version.new(Gem::VERSION) >= Gem::Version.new("1.8.0")
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new("2.7")
+ allow(@gem_env).to receive(:gem_specification).and_return(Gem::Specification)
+ expect(Gem::Specification).to receive(:dirs).and_return(["/path/to/gems/specifications", "/another/path/to/gems/specifications"])
+ expect(Gem::Specification).to receive(:installed_stubs).with(["/path/to/gems/specifications", "/another/path/to/gems/specifications"], "rspec-*.gemspec").and_return(gems)
+ elsif Gem::Version.new(Gem::VERSION) >= Gem::Version.new("1.8.0")
allow(@gem_env).to receive(:gem_specification).and_return(Gem::Specification)
expect(@gem_env.gem_specification).to receive(:find_all_by_name).with(rspec_dep.name, rspec_dep.requirement).and_return(gems)
else
@@ -244,34 +253,34 @@ 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
-RubyGems Environment:
- - RUBYGEMS VERSION: 1.3.6
- - RUBY VERSION: 1.8.7 (2010-05-12 patchlevel 249) [java]
- - INSTALLATION DIRECTORY: /Users/you/.rvm/gems/jruby-1.5.0
- - RUBY EXECUTABLE: /Users/you/.rvm/rubies/jruby-1.5.0/bin/jruby
- - EXECUTABLE DIRECTORY: /Users/you/.rvm/gems/jruby-1.5.0/bin
- - RUBYGEMS PLATFORMS:
- - ruby
- - universal-java-1.6
- - GEM PATHS:
- - /Users/you/.rvm/gems/jruby-1.5.0
- - /Users/you/.rvm/gems/jruby-1.5.0@global
- - GEM CONFIGURATION:
- - :update_sources => true
- - :verbose => true
- - :benchmark => false
- - :backtrace => false
- - :bulk_threshold => 1000
- - "install" => "--env-shebang"
- - "update" => "--env-shebang"
- - "gem" => "--no-rdoc --no-ri"
- - :sources => ["https://rubygems.org/", "http://gems.github.com/"]
- - REMOTE SOURCES:
- - https://rubygems.org/
- - http://gems.github.com/
+ gem_env_out = <<~JRUBY_GEM_ENV
+ RubyGems Environment:
+ - RUBYGEMS VERSION: 1.3.6
+ - RUBY VERSION: 1.8.7 (2010-05-12 patchlevel 249) [java]
+ - INSTALLATION DIRECTORY: /Users/you/.rvm/gems/jruby-1.5.0
+ - RUBY EXECUTABLE: /Users/you/.rvm/rubies/jruby-1.5.0/bin/jruby
+ - EXECUTABLE DIRECTORY: /Users/you/.rvm/gems/jruby-1.5.0/bin
+ - RUBYGEMS PLATFORMS:
+ - ruby
+ - universal-java-1.6
+ - GEM PATHS:
+ - /Users/you/.rvm/gems/jruby-1.5.0
+ - /Users/you/.rvm/gems/jruby-1.5.0@global
+ - GEM CONFIGURATION:
+ - :update_sources => true
+ - :verbose => true
+ - :benchmark => false
+ - :backtrace => false
+ - :bulk_threshold => 1000
+ - "install" => "--env-shebang"
+ - "update" => "--env-shebang"
+ - "gem" => "--no-rdoc --no-ri"
+ - :sources => ["https://rubygems.org/", "http://gems.github.com/"]
+ - REMOTE SOURCES:
+ - https://rubygems.org/
+ - http://gems.github.com/
JRUBY_GEM_ENV
- expect(@gem_env).to receive(:shell_out!).with("/usr/weird/bin/gem env").and_return(double("jruby_gem_env", stdout: gem_env_out))
+ expect(@gem_env).to receive(:shell_out_compacted!).with("/usr/weird/bin/gem env").and_return(double("jruby_gem_env", stdout: gem_env_out))
expected = ["ruby", Gem::Platform.new("universal-java-1.6")]
expect(@gem_env.gem_platforms).to eq(expected)
# it should also cache the result
@@ -279,41 +288,41 @@ RubyGems Environment:
end
it "uses the cached result for gem platforms if available" do
- expect(@gem_env).not_to receive(:shell_out!)
+ expect(@gem_env).not_to receive(:shell_out_compacted!)
expected = ["ruby", Gem::Platform.new("universal-java-1.6")]
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
-RubyGems Environment:
- - RUBYGEMS VERSION: 1.3.6
- - RUBY VERSION: 1.8.7 (2010-05-14 patchlevel 174) [x86_64-apple-darwin10.3.0]
- - INSTALLATION DIRECTORY: /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514
- - RUBYGEMS PREFIX: /Users/ddeleo/.rvm/rubies/rbx-1.0.0-20100514
- - RUBY EXECUTABLE: /Users/ddeleo/.rvm/rubies/rbx-1.0.0-20100514/bin/rbx
- - EXECUTABLE DIRECTORY: /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514/bin
- - RUBYGEMS PLATFORMS:
- - ruby
- - x86_64-darwin-10
- - x86_64-rubinius-1.0
- - GEM PATHS:
- - /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514
- - /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514@global
- - GEM CONFIGURATION:
- - :update_sources => true
- - :verbose => true
- - :benchmark => false
- - :backtrace => false
- - :bulk_threshold => 1000
- - :sources => ["https://rubygems.org/", "http://gems.github.com/"]
- - "gem" => "--no-rdoc --no-ri"
- - REMOTE SOURCES:
- - https://rubygems.org/
- - http://gems.github.com/
+ 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]
+ - INSTALLATION DIRECTORY: /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514
+ - RUBYGEMS PREFIX: /Users/ddeleo/.rvm/rubies/rbx-1.0.0-20100514
+ - RUBY EXECUTABLE: /Users/ddeleo/.rvm/rubies/rbx-1.0.0-20100514/bin/rbx
+ - EXECUTABLE DIRECTORY: /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514/bin
+ - RUBYGEMS PLATFORMS:
+ - ruby
+ - x86_64-darwin-10
+ - x86_64-rubinius-1.0
+ - GEM PATHS:
+ - /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514
+ - /Users/ddeleo/.rvm/gems/rbx-1.0.0-20100514@global
+ - GEM CONFIGURATION:
+ - :update_sources => true
+ - :verbose => true
+ - :benchmark => false
+ - :backtrace => false
+ - :bulk_threshold => 1000
+ - :sources => ["https://rubygems.org/", "http://gems.github.com/"]
+ - "gem" => "--no-rdoc --no-ri"
+ - REMOTE SOURCES:
+ - https://rubygems.org/
+ - http://gems.github.com/
RBX_GEM_ENV
- expect(@gem_env).to receive(:shell_out!).with("/usr/weird/bin/gem env").and_return(double("rbx_gem_env", stdout: gem_env_out))
+ expect(@gem_env).to receive(:shell_out_compacted!).with("/usr/weird/bin/gem env").and_return(double("rbx_gem_env", stdout: gem_env_out))
expect(@gem_env.gem_platforms).to eq(Gem.platforms)
expect(Chef::Provider::Package::Rubygems::AlternateGemEnvironment.platform_cache["/usr/weird/bin/gem"]).to eq(Gem.platforms)
end
@@ -383,6 +392,11 @@ describe Chef::Provider::Package::Rubygems do
provider.load_current_resource
expect(provider.target_version_already_installed?(provider.current_resource.version, new_resource.version)).to be_falsey
end
+
+ it "version_equals? should return false so that we can search for candidates" do
+ provider.load_current_resource
+ expect(provider.version_equals?(provider.current_resource.version, new_resource.version)).to be_falsey
+ end
end
describe "when new_resource version is an rspec version" do
@@ -670,7 +684,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem by shelling out when options are provided as a String" do
expected = "gem install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://www.rubygems.org #{options}"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -683,7 +697,7 @@ describe Chef::Provider::Package::Rubygems do
Chef::Config[:rubygems_url] = "https://mirror1"
expect(provider.gem_env).to receive(:candidate_version_from_remote).with(gem_dep, Chef::Config[:rubygems_url]).and_return(version)
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://mirror1"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -695,7 +709,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem with rubygems.org as an added source" do
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=#{source} --source=https://www.rubygems.org"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -706,7 +720,7 @@ describe Chef::Provider::Package::Rubygems do
it "ignores the Chef::Config setting" do
Chef::Config[:rubygems_url] = "https://ignored"
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=#{source}"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -719,7 +733,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem with an array as an added source" do
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://mirror1 --source=https://mirror2 --source=https://www.rubygems.org"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -730,7 +744,7 @@ describe Chef::Provider::Package::Rubygems do
it "ignores the Chef::Config setting" do
Chef::Config[:rubygems_url] = "https://ignored"
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://mirror1 --source=https://mirror2"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -744,7 +758,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem" do
new_resource.clear_sources(true)
expected = "#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --clear-sources --source=#{source} --source=https://www.rubygems.org"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -756,7 +770,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem by shelling out when options are provided but no version is given" do
expected = "gem install rspec-core -q --no-rdoc --no-ri -v \"#{candidate_version}\" --source=https://www.rubygems.org #{options}"
- expect(provider).to receive(:shell_out!).with(expected, env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with(expected, env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -819,7 +833,7 @@ describe Chef::Provider::Package::Rubygems do
let(:gem_binary) { "/usr/weird/bin/gem" }
it "installs the gem by shelling out to gem install" do
- expect(provider).to receive(:shell_out!).with("#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://www.rubygems.org", env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("#{gem_binary} install rspec-core -q --no-rdoc --no-ri -v \"#{target_version}\" --source=https://www.rubygems.org", env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -829,7 +843,7 @@ describe Chef::Provider::Package::Rubygems do
let(:target_version) { ">= 0" }
it "installs the gem by shelling out to gem install" do
- expect(provider).to receive(:shell_out!).with("#{gem_binary} install #{source} -q --no-rdoc --no-ri -v \"#{target_version}\"", env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("#{gem_binary} install #{source} -q --no-rdoc --no-ri -v \"#{target_version}\"", env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -841,7 +855,7 @@ describe Chef::Provider::Package::Rubygems do
it "installs the gem from file by shelling out to gem install when the package is a path and the source is nil" do
expect(new_resource.source).to eq(gem_name)
- expect(provider).to receive(:shell_out!).with("#{gem_binary} install #{gem_name} -q --no-rdoc --no-ri -v \"#{target_version}\"", env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("#{gem_binary} install #{gem_name} -q --no-rdoc --no-ri -v \"#{target_version}\"", env: nil, timeout: 900)
provider.run_action(:install)
expect(new_resource).to be_updated_by_last_action
end
@@ -888,7 +902,7 @@ describe Chef::Provider::Package::Rubygems do
let(:options) { "-i /alt/install/location" }
it "uninstalls via the gem command" do
- expect(provider).to receive(:shell_out!).with("gem uninstall rspec -q -x -I -a #{options}", env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("gem uninstall rspec -q -x -I -a #{options}", env: nil, timeout: 900)
provider.action_remove
end
end
@@ -907,7 +921,7 @@ describe Chef::Provider::Package::Rubygems do
let(:gem_binary) { "/usr/weird/bin/gem" }
it "uninstalls via the gem command" do
- expect(provider).to receive(:shell_out!).with("#{gem_binary} uninstall rspec -q -x -I -a", env: nil, timeout: 900)
+ expect(provider).to receive(:shell_out_compacted!).with("#{gem_binary} uninstall rspec -q -x -I -a", env: nil, timeout: 900)
provider.action_remove
end
end
diff --git a/spec/unit/provider/package/smartos_spec.rb b/spec/unit/provider/package/smartos_spec.rb
index 51bffa17b6..cd85e1b3d9 100644
--- a/spec/unit/provider/package/smartos_spec.rb
+++ b/spec/unit/provider/package/smartos_spec.rb
@@ -28,39 +28,39 @@ 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)
+ @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)
@stdin = StringIO.new
@stdout = "varnish-2.1.5nb2\n"
@stderr = StringIO.new
@pid = 10
- @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
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(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
expect(Chef::Resource::Package).to receive(:new).and_return(@current_resource)
@provider.load_current_resource
end
it "should set the current resource package name" do
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
expect(@current_resource).to receive(:package_name).with(@new_resource.package_name)
@provider.load_current_resource
end
it "should set the installed version if it is installed" do
- expect(@provider).to receive(:shell_out!).and_return(@shell_out)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(@shell_out)
@provider.load_current_resource
expect(@current_resource.version).to eq("2.1.5nb2")
end
it "should set the installed version to nil if it's not installed" do
- out = OpenStruct.new(:stdout => nil)
- expect(@provider).to receive(:shell_out!).and_return(out)
+ out = OpenStruct.new(stdout: nil)
+ expect(@provider).to receive(:shell_out_compacted!).and_return(out)
@provider.load_current_resource
expect(@current_resource.version).to eq(nil)
end
@@ -70,27 +70,27 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do
describe "candidate_version" do
it "should return the candidate_version variable if already setup" do
@provider.candidate_version = "2.1.1"
- expect(@provider).not_to receive(:shell_out!)
+ expect(@provider).not_to receive(:shell_out_compacted!)
@provider.candidate_version
end
it "should lookup the candidate_version if the variable is not already set (pkgin separated by spaces)" do
search = double()
- expect(search).to receive(:each_line).
- 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(search).to receive(:each_line)
+ .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_compacted!).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
it "should lookup the candidate_version if the variable is not already set (pkgin separated by semicolons)" do
search = double()
- expect(search).to receive(:each_line).
- 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(search).to receive(:each_line)
+ .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_compacted!).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
@@ -98,9 +98,9 @@ describe Chef::Provider::Package::SmartOS, "load_current_resource" do
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)
+ out = OpenStruct.new(stdout: nil)
+ expect(@provider).to receive(:shell_out_compacted!).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_compacted!).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
diff --git a/spec/unit/provider/package/solaris_spec.rb b/spec/unit/provider/package/solaris_spec.rb
index 2fba2e3a08..2aa37fe8b3 100644
--- a/spec/unit/provider/package/solaris_spec.rb
+++ b/spec/unit/provider/package/solaris_spec.rb
@@ -32,37 +32,37 @@ describe Chef::Provider::Package::Solaris do
describe "assessing the current package status" do
before do
- @pkginfo = <<-PKGINFO
-PKGINST: SUNWbash
-NAME: GNU Bourne-Again shell (bash)
-CATEGORY: system
-ARCH: sparc
-VERSION: 11.10.0,REV=2005.01.08.05.16
-BASEDIR: /
-VENDOR: Sun Microsystems, Inc.
-DESC: GNU Bourne-Again shell (bash) version 3.0
-PSTAMP: sfw10-patch20070430084444
-INSTDATE: Nov 04 2009 01:02
-HOTLINE: Please contact your local service provider
+ @pkginfo = <<~PKGINFO
+ PKGINST: SUNWbash
+ NAME: GNU Bourne-Again shell (bash)
+ CATEGORY: system
+ ARCH: sparc
+ VERSION: 11.10.0,REV=2005.01.08.05.16
+ BASEDIR: /
+ VENDOR: Sun Microsystems, Inc.
+ DESC: GNU Bourne-Again shell (bash) version 3.0
+ PSTAMP: sfw10-patch20070430084444
+ 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
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@provider.load_current_resource
expect(@provider.current_resource.name).to eq("SUNWbash")
end
it "should set the current reource package name to the new resource package name" do
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("SUNWbash")
end
it "should raise an exception if a source is supplied but not found" do
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
allow(::File).to receive(:exist?).and_return(false)
@provider.load_current_resource
@provider.define_resource_requirements
@@ -70,9 +70,9 @@ PKGINFO
end
it "should get the source package version from pkginfo if provided" do
- status = double(:stdout => @pkginfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(status)
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(@status)
+ status = double(stdout: @pkginfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(@status)
@provider.load_current_resource
expect(@provider.current_resource.package_name).to eq("SUNWbash")
@@ -80,9 +80,9 @@ PKGINFO
end
it "should return the current version installed if found by pkginfo" do
- status = double(:stdout => @pkginfo, :exitstatus => 0)
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(@status)
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(status)
+ status = double(stdout: @pkginfo, exitstatus: 0)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(@status)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(status)
@provider.load_current_resource
expect(@provider.current_resource.version).to eq("11.10.0,REV=2005.01.08.05.16")
end
@@ -90,19 +90,19 @@ PKGINFO
it "should raise an exception if the source is not set but we are installing" do
@new_resource = Chef::Resource::Package.new("SUNWbash")
@provider = Chef::Provider::Package::Solaris.new(@new_resource, @run_context)
- allow(@provider).to receive(:shell_out).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted).and_return(@status)
expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
end
it "should raise an exception if pkginfo fails to run" do
- status = double(:stdout => "", :exitstatus => -1)
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "", exitstatus: -1)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
end
it "should return a current resource with a nil version if the package is not found" do
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(@status)
- expect(@provider).to receive(:shell_out).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(@status)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "-d", "/tmp/bash.pkg", "SUNWbash", { timeout: 900 }).and_return(@status)
+ expect(@provider).to receive(:shell_out_compacted).with("pkginfo", "-l", "SUNWbash", { timeout: 900 }).and_return(@status)
@provider.load_current_resource
expect(@provider.current_resource.version).to be_nil
end
@@ -111,20 +111,20 @@ PKGINFO
describe "candidate_version" do
it "should return the candidate_version variable if already setup" do
@provider.candidate_version = "11.10.0,REV=2005.01.08.05.16"
- expect(@provider).not_to receive(:shell_out)
+ expect(@provider).not_to receive(:shell_out_compacted)
@provider.candidate_version
end
it "should lookup the candidate_version if the variable is not already set" do
- status = double(:stdout => "", :exitstatus => 0)
- allow(@provider).to receive(:shell_out).and_return(status)
- expect(@provider).to receive(:shell_out)
+ status = double(stdout: "", exitstatus: 0)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
+ expect(@provider).to receive(:shell_out_compacted)
@provider.candidate_version
end
it "should throw and exception if the exitstatus is not 0" do
- status = double(:stdout => "", :exitstatus => 1)
- allow(@provider).to receive(:shell_out).and_return(status)
+ status = double(stdout: "", exitstatus: 1)
+ allow(@provider).to receive(:shell_out_compacted).and_return(status)
expect { @provider.candidate_version }.to raise_error(Chef::Exceptions::Package)
end
@@ -132,7 +132,7 @@ PKGINFO
describe "install and upgrade" do
it "should run pkgadd -n -d with the package source to install" do
- expect(@provider).to receive(:shell_out!).with("pkgadd", "-n", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("pkgadd", "-n", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
@provider.install_package("SUNWbash", "11.10.0,REV=2005.01.08.05.16")
end
@@ -140,26 +140,26 @@ PKGINFO
@new_resource = Chef::Resource::Package.new("/tmp/bash.pkg")
@provider = Chef::Provider::Package::Solaris.new(@new_resource, @run_context)
expect(@new_resource.source).to eq("/tmp/bash.pkg")
- expect(@provider).to receive(:shell_out!).with("pkgadd", "-n", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("pkgadd", "-n", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
@provider.install_package("/tmp/bash.pkg", "11.10.0,REV=2005.01.08.05.16")
end
it "should run pkgadd -n -a /tmp/myadmin -d with the package options -a /tmp/myadmin" do
@new_resource.options "-a /tmp/myadmin"
- expect(@provider).to receive(:shell_out!).with("pkgadd", "-n", "-a", "/tmp/myadmin", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("pkgadd", "-n", "-a", "/tmp/myadmin", "-d", "/tmp/bash.pkg", "all", { timeout: 900 })
@provider.install_package("SUNWbash", "11.10.0,REV=2005.01.08.05.16")
end
end
describe "remove" do
it "should run pkgrm -n to remove the package" do
- expect(@provider).to receive(:shell_out!).with("pkgrm", "-n", "SUNWbash", { timeout: 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("pkgrm", "-n", "SUNWbash", { timeout: 900 })
@provider.remove_package("SUNWbash", "11.10.0,REV=2005.01.08.05.16")
end
it "should run pkgrm -n -a /tmp/myadmin with options -a /tmp/myadmin" do
@new_resource.options "-a /tmp/myadmin"
- expect(@provider).to receive(:shell_out!).with("pkgrm", "-n", "-a", "/tmp/myadmin", "SUNWbash", { timeout: 900 })
+ expect(@provider).to receive(:shell_out_compacted!).with("pkgrm", "-n", "-a", "/tmp/myadmin", "SUNWbash", { timeout: 900 })
@provider.remove_package("SUNWbash", "11.10.0,REV=2005.01.08.05.16")
end
diff --git a/spec/unit/provider/package/windows/exe_spec.rb b/spec/unit/provider/package/windows/exe_spec.rb
index f18cbf3dca..f8c4e83fc5 100644
--- a/spec/unit/provider/package/windows/exe_spec.rb
+++ b/spec/unit/provider/package/windows/exe_spec.rb
@@ -126,7 +126,7 @@ describe Chef::Provider::Package::Windows::Exe do
it "removes installed package and quotes uninstall string" do
new_resource.timeout = 300
allow(::File).to receive(:exist?).with("uninst_dir/uninst_file").and_return(true)
- expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir\/uninst_file\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, :timeout => 300, :returns => [0])
+ expect(provider).to receive(:shell_out!).with(/start \"\" \/wait \"uninst_dir\/uninst_file\" \/S \/NCRC & exit %%%%ERRORLEVEL%%%%/, timeout: 300, returns: [0])
provider.remove_package
end
end
diff --git a/spec/unit/provider/package/windows/msi_spec.rb b/spec/unit/provider/package/windows/msi_spec.rb
index aa528ab90e..0e939610db 100644
--- a/spec/unit/provider/package/windows/msi_spec.rb
+++ b/spec/unit/provider/package/windows/msi_spec.rb
@@ -22,7 +22,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(:run_context) { double("Chef::RunContext", :node => node, :events => events) }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events) }
let(:package_name) { "calculator" }
let(:resource_source) { "calculator.msi" }
let(:resource_version) { nil }
diff --git a/spec/unit/provider/package/windows_spec.rb b/spec/unit/provider/package/windows_spec.rb
index d07e68cb5b..3030b7f04a 100644
--- a/spec/unit/provider/package/windows_spec.rb
+++ b/spec/unit/provider/package/windows_spec.rb
@@ -50,7 +50,7 @@ describe Chef::Provider::Package::Windows, :windows_only do
before(:each) do
allow(Chef::Util::PathHelper).to receive(:validate_path)
allow(provider).to receive(:package_provider).and_return(double("package_provider",
- :installed_version => "1.0", :package_version => "2.0"))
+ installed_version: "1.0", package_version: "2.0"))
end
it "creates a current resource with the name of the new resource" do
@@ -394,6 +394,25 @@ describe Chef::Provider::Package::Windows, :windows_only do
end
end
end
+
+ context "a missing local file is given" do
+ let(:resource_source) { "C:/a_missing_file.exe" }
+ let(:installer_type) { nil }
+ before do
+ allow(::File).to receive(:exist?).with(provider.new_resource.source).and_return(false)
+ provider.load_current_resource
+ end
+
+ it "raises a Package error" do
+ expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
+ end
+
+ it "why_run mode doesn't raise an error" do
+ Chef::Config[:why_run] = true
+ expect { provider.run_action(:install) }.not_to raise_error
+ Chef::Config[:why_run] = false
+ end
+ end
end
shared_context "valid checksum" do
diff --git a/spec/unit/provider/package/yum/python_helper_spec.rb b/spec/unit/provider/package/yum/python_helper_spec.rb
new file mode 100644
index 0000000000..ba91e2f24a
--- /dev/null
+++ b/spec/unit/provider/package/yum/python_helper_spec.rb
@@ -0,0 +1,29 @@
+#
+# Copyright:: Copyright 2017-2017, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+# NOTE: most of the tests of this functionality are baked into the func tests for the yum package provider
+
+describe Chef::Provider::Package::Yum::PythonHelper do
+ let(:helper) { Chef::Provider::Package::Yum::PythonHelper.instance }
+
+ it "propagates stacktraces on stderr from the forked subprocess", :rhel do
+ allow(helper).to receive(:yum_command).and_return("ruby -e 'raise \"your hands in the air\"'")
+ expect { helper.package_query(:whatprovides, "tcpdump") }.to raise_error(/your hands in the air/)
+ end
+end
diff --git a/spec/unit/provider/package/yum/yum_cache_spec.rb b/spec/unit/provider/package/yum/yum_cache_spec.rb
index e9d615d734..6b2a617ac8 100644
--- a/spec/unit/provider/package/yum/yum_cache_spec.rb
+++ b/spec/unit/provider/package/yum/yum_cache_spec.rb
@@ -1,6 +1,5 @@
#
-# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software, Inc.
+# Copyright:: Copyright 2018-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,9 +18,92 @@
require "spec_helper"
describe Chef::Provider::Package::Yum::YumCache do
+ let(:yum_cache) { Chef::Provider::Package::Yum::YumCache.instance }
- it "can find yum-dump.py" do
- expect(File.exist?(Chef::Provider::Package::Yum::YumCache.instance.yum_dump_path)).to be true
+ let(:python_helper) { instance_double(Chef::Provider::Package::Yum::PythonHelper) }
+
+ def yum_version(name, version, arch)
+ Chef::Provider::Package::Yum::Version.new(name, version, arch)
+ end
+
+ before(:each) do
+ allow( yum_cache ).to receive(:python_helper).and_return(python_helper)
+ end
+
+ it "package_available? returns false if the helper reports the available version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: nil).and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.package_available?("foo") ).to be false
+ end
+
+ it "package_available? returns true if the helper returns an available version" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: nil).and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.package_available?("foo") ).to be true
+ end
+
+ it "version_available? returns false if the helper reports the available version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", version: "1.2.3", arch: nil).and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.version_available?("foo", "1.2.3") ).to be false
+ end
+
+ it "version_available? returns true if the helper returns an available version" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", version: "1.2.3", arch: nil).and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.version_available?("foo", "1.2.3") ).to be true
+ end
+
+ it "version_available? with an arch returns false if the helper reports the available version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", version: "1.2.3", arch: "x86_64").and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.version_available?("foo", "1.2.3", "x86_64") ).to be false
+ end
+
+ it "version_available? with an arch returns true if the helper returns an available version" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", version: "1.2.3", arch: "x86_64").and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.version_available?("foo", "1.2.3", "x86_64") ).to be true
+ end
+
+ [ :refresh, :reload, :reload_installed, :reload_provides, :reset, :reset_installed ].each do |method|
+ it "restarts the python helper when #{method} is called" do
+ expect( python_helper ).to receive(:restart)
+ yum_cache.send(method)
+ end
+ end
+
+ it "installed_version? returns nil if the helper reports the installed version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatinstalled, "foo", arch: nil).and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.installed_version("foo") ).to be nil
+ end
+
+ it "installed_version? returns version string if the helper returns an installed version" do
+ expect( python_helper ).to receive(:package_query).with(:whatinstalled, "foo", arch: nil).and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.installed_version("foo") ).to eql("1.2.3-1.x86_64")
+ end
+
+ it "installed_version? returns nil if the helper reports the installed version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatinstalled, "foo", arch: "x86_64").and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.installed_version("foo", "x86_64") ).to be nil
+ end
+
+ it "installed_version? returns version string if the helper returns an installed version" do
+ expect( python_helper ).to receive(:package_query).with(:whatinstalled, "foo", arch: "x86_64").and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.installed_version("foo", "x86_64") ).to eql("1.2.3-1.x86_64")
+ end
+
+ it "available_version? returns nil if the helper reports the available version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: nil).and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.available_version("foo") ).to be nil
+ end
+
+ it "available_version? returns version string if the helper returns an available version" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: nil).and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.available_version("foo") ).to eql("1.2.3-1.x86_64")
+ end
+
+ it "available_version? returns nil if the helper reports the available version is nil" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: "x86_64").and_return( yum_version("foo", nil, nil) )
+ expect( yum_cache.available_version("foo", "x86_64") ).to be nil
end
+ it "available_version? returns version string if the helper returns an available version" do
+ expect( python_helper ).to receive(:package_query).with(:whatavailable, "foo", arch: "x86_64").and_return( yum_version("foo", "1.2.3-1", "x86_64") )
+ expect( yum_cache.available_version("foo", "x86_64") ).to eql("1.2.3-1.x86_64")
+ end
end
diff --git a/spec/unit/provider/package/yum_spec.rb b/spec/unit/provider/package/yum_spec.rb
deleted file mode 100644
index c8fb04cc21..0000000000
--- a/spec/unit/provider/package/yum_spec.rb
+++ /dev/null
@@ -1,2294 +0,0 @@
-#
-# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-require "securerandom"
-
-describe Chef::Provider::Package::Yum do
- before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @new_resource = Chef::Resource::YumPackage.new("cups")
- @status = double("Status", :exitstatus => 0)
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5_2.3",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [ "kernel" ],
- :package_repository => "base",
- :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(::File).to receive(:exist?).with("/usr/bin/yum-deprecated").and_return(false)
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @pid = double("PID")
- end
-
- describe "when loading the current system state" do
- it "should create a current resource with the name of the new_resource" do
- @provider.load_current_resource
- expect(@provider.current_resource.name).to eq("cups")
- end
-
- it "should set the current resources package name to the new resources package name" do
- @provider.load_current_resource
- expect(@provider.current_resource.package_name).to eq("cups")
- end
-
- it "should set the installed version to nil on the current resource if no installed package" do
- allow(@yum_cache).to receive(:installed_version).and_return(nil)
- @provider.load_current_resource
- expect(@provider.current_resource.version).to be_nil
- end
-
- it "should set the installed version if yum has one" do
- @provider.load_current_resource
- expect(@provider.current_resource.version).to eq("1.2.4-11.18.el5")
- end
-
- it "should set the candidate version if yum info has one" do
- @provider.load_current_resource
- expect(@provider.candidate_version).to eql("1.2.4-11.18.el5_2.3")
- end
-
- it "should return the current resouce" do
- expect(@provider.load_current_resource).to eql(@provider.current_resource)
- end
-
- describe "when source is provided" do
- it "should set the candidate version" do
- @new_resource = Chef::Resource::YumPackage.new("testing.source")
- @new_resource.source "chef-server-core-12.0.5-1.rpm"
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- allow(File).to receive(:exist?).with(@new_resource.source).and_return(true)
- allow(@yum_cache).to receive(:installed_version).and_return(nil)
- shellout_double = double(:stdout => "chef-server-core 12.0.5-1 i386")
- allow(@provider).to receive(:shell_out!).and_return(shellout_double)
- @provider.load_current_resource
- expect(@provider.candidate_version).to eql("12.0.5-1")
- expect(@provider.new_resource.arch).to eql("i386")
- end
- end
-
- describe "yum_binary accessor" do
- it "when yum-deprecated exists" do
- expect(File).to receive(:exist?).with("/usr/bin/yum-deprecated").and_return(true)
- expect(@yum_cache).to receive(:yum_binary=).with("yum-deprecated")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@provider.send(:yum_binary)).to eql("yum-deprecated")
- end
-
- it "when yum-deprecated does not exist" do
- expect(File).to receive(:exist?).with("/usr/bin/yum-deprecated").and_return(false)
- expect(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@provider.send(:yum_binary)).to eql("yum")
- end
-
- it "when the yum_binary is set on the resource" do
- @new_resource.yum_binary "/usr/bin/yum-something"
- expect(File).not_to receive(:exist?)
- expect(@yum_cache).to receive(:yum_binary=).with("/usr/bin/yum-something")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@provider.send(:yum_binary)).to eql("/usr/bin/yum-something")
- end
-
- it "when the new_resource is a vanilla package class and yum-deprecated exists" do
- @new_resource = Chef::Resource::YumPackage.new("cups")
- expect(File).to receive(:exist?).with("/usr/bin/yum-deprecated").and_return(true)
- expect(@yum_cache).to receive(:yum_binary=).with("yum-deprecated")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@provider.send(:yum_binary)).to eql("yum-deprecated")
- end
-
- it "when the new_resource is a vanilla package class and yum-deprecated does not exist" do
- @new_resource = Chef::Resource::YumPackage.new("cups")
- expect(File).to receive(:exist?).with("/usr/bin/yum-deprecated").and_return(false)
- expect(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@provider.send(:yum_binary)).to eql("yum")
- end
- end
-
- describe "when arch in package_name" do
- it "should set the arch if no existing package_name is found and new_package_name+new_arch is available" do
- @new_resource = Chef::Resource::YumPackage.new("testing.noarch")
- @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(:candidate_version) do |package_name, arch|
- if package_name == "testing.noarch" || package_name == "testing.more.noarch"
- nil
- # candidate for new_package_name
- elsif package_name == "testing" || package_name == "testing.more"
- "1.1"
- end
- end
- allow(@yum_cache).to receive(:package_available?).and_return(true)
- allow(@yum_cache).to receive(:disable_extra_repo_control).and_return(true)
- allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache)
- allow(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing")
- expect(@provider.new_resource.arch).to eq("noarch")
-
- @new_resource = Chef::Resource::YumPackage.new("testing.more.noarch")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.more")
- expect(@provider.new_resource.arch).to eq("noarch")
- end
-
- describe "when version constraint in package_name" do
- it "should set package_version if no existing package_name is found and new_package_name is available" do
- @new_resource = Chef::Resource::YumPackage.new("cups = 1.2.4-11.18.el5_2.3")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- allow(@yum_cache).to receive(:package_available?) { |pkg| pkg == "cups" ? true : false }
- allow(@yum_cache).to receive(:packages_from_require) do |pkg|
- [Chef::Provider::Package::Yum::RPMDbPackage.new("cups", "1.2.4-11.18.el5_2.3", "noarch", [], false, true, "base"),
- Chef::Provider::Package::Yum::RPMDbPackage.new("cups", "1.2.4-11.18.el5_2.2", "noarch", [], false, true, "base")]
- end
- expect(Chef::Log).to receive(:debug).exactly(1).times.with(%r{checking yum info})
- expect(Chef::Log).to receive(:debug).exactly(1).times.with(%r{installed version})
- expect(Chef::Log).to receive(:debug).exactly(1).times.with(%r{matched 2 packages,})
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("cups")
- expect(@provider.new_resource.version).to eq("1.2.4-11.18.el5_2.3")
- expect(@provider.send(:new_version_array)).to eq(["1.2.4-11.18.el5_2.3"])
- expect(@provider.send(:package_name_array)).to eq(["cups"])
- end
- end
-
- it "should not set the arch when an existing package_name is found" do
- @new_resource = Chef::Resource::YumPackage.new("testing.beta3")
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache"
- )
- allow(@yum_cache).to receive(:installed_version) do |package_name, arch|
- # installed for package_name
- if package_name == "testing.beta3" || package_name == "testing.beta3.more"
- "1.1"
- elsif package_name == "testing" || package_name == "testing.beta3"
- nil
- end
- end
- allow(@yum_cache).to receive(:candidate_version) do |package_name, arch|
- # no candidate for package_name/new_package_name
- nil
- end
- allow(@yum_cache).to receive(:package_available?).and_return(true)
- allow(@yum_cache).to receive(:disable_extra_repo_control).and_return(true)
- allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache)
- allow(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- # annoying side effect of the fun stub'ing above
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.beta3")
- expect(@provider.new_resource.arch).to eq(nil)
-
- @new_resource = Chef::Resource::YumPackage.new("testing.beta3.more")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.beta3.more")
- expect(@provider.new_resource.arch).to eq(nil)
- end
-
- it "should not set the arch when no existing package_name or new_package_name+new_arch is found" do
- @new_resource = Chef::Resource::YumPackage.new("testing.beta3")
- @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(:candidate_version) do |package_name, arch|
- # no candidate for package_name/new_package_name
- nil
- end
- allow(@yum_cache).to receive(:package_available?).and_return(true)
- allow(@yum_cache).to receive(:disable_extra_repo_control).and_return(true)
- allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache)
- allow(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.beta3")
- expect(@provider.new_resource.arch).to eq(nil)
-
- @new_resource = Chef::Resource::YumPackage.new("testing.beta3.more")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.beta3.more")
- expect(@provider.new_resource.arch).to eq(nil)
- end
-
- it "should ensure it doesn't clobber an existing arch if passed" do
- @new_resource = Chef::Resource::YumPackage.new("testing.i386")
- @new_resource.arch("x86_64")
- @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(:candidate_version) do |package_name, arch|
- if package_name == "testing.noarch"
- nil
- # candidate for new_package_name
- elsif package_name == "testing"
- "1.1"
- end
- end.and_return("something")
- allow(@yum_cache).to receive(:package_available?).and_return(true)
- allow(@yum_cache).to receive(:disable_extra_repo_control).and_return(true)
- allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(@yum_cache)
- allow(@yum_cache).to receive(:yum_binary=).with("yum")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq("testing.i386")
- expect(@provider.new_resource.arch).to eq("x86_64")
- end
- end
-
- it "should flush the cache if :before is true" do
- @new_resource.flush_cache({ :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
- @new_resource.flush_cache({ :after => false, :before => false })
- expect(@yum_cache).not_to receive(:reload)
- @provider.load_current_resource
- end
-
- it "should detect --enablerepo or --disablerepo when passed among options, collect them preserving order and notify the yum cache" do
- @new_resource.options("--stuff --enablerepo=foo --otherthings --disablerepo=a,b,c --enablerepo=bar")
- expect(@yum_cache).to receive(:enable_extra_repo_control).with("--enablerepo=foo --disablerepo=a,b,c --enablerepo=bar")
- @provider.load_current_resource
- end
-
- it "should let the yum cache know extra repos are disabled if --enablerepo or --disablerepo aren't among options" do
- @new_resource.options("--stuff --otherthings")
- expect(@yum_cache).to receive(:disable_extra_repo_control)
- @provider.load_current_resource
- end
-
- it "should let the yum cache know extra repos are disabled if options aren't set" do
- @new_resource.options(nil)
- expect(@yum_cache).to receive(:disable_extra_repo_control)
- @provider.load_current_resource
- end
-
- context "when the package name isn't found" do
- let(:yum_cache) do
- double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.0.1.el5",
- :candidate_version => "2.0.1.el5",
- :package_available? => false,
- :version_available? => true,
- :disable_extra_repo_control => true
- )
- end
-
- before do
- allow(Chef::Provider::Package::Yum::YumCache).to receive(:instance).and_return(yum_cache)
- 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])
- end
-
- it "should search provides then set package_name to match" do
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@new_resource.package_name).to eq("test-package")
- expect(@new_resource.version).to eq(nil)
- end
-
- it "should search provides then set version to match if a requirement was passed in the package name" do
- @new_resource = Chef::Resource::YumPackage.new("test-package = 2.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")
- 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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@new_resource.package_name).to eq("test-package")
- 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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@new_resource.package_name).to eq("test-package")
- expect(@new_resource.version).to eq("3.0.1.el5")
- end
-
- it "should search provides then set versions to match if requirements were passed in the package name as an array" do
- @new_resource = Chef::Resource::YumPackage.new(["test-package = 2.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"])
- expect(@new_resource.version).to eq(["2.0.1.el5"])
- end
-
- it "should search provides and not set the versions to match if specific versions were requested in an array" do
- @new_resource = Chef::Resource::YumPackage.new(["test-package"])
- @new_resource.version(["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"])
- 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
- @new_resource = Chef::Resource::YumPackage.new("test-package")
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.0.1.el5",
- :candidate_version => "2.0.1.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
- 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)
- @provider.load_current_resource
- expect(@new_resource.package_name).to eq("test-package")
- expect(@new_resource.version).to eq(nil)
- end
-
- it "should give precedence to the version attribute when both a requirement in the resource name and a version attribute are specified" do
- @new_resource = Chef::Resource::YumPackage.new("test-package")
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
- 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")
- @new_resource.version("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")
- expect(@new_resource.version).to eq("3.0.1.el5")
- end
-
- it "should correctly detect the installed states of an array of package names and version numbers" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.0.1.el5",
- :candidate_version => "2.0.1.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
-
- 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"])
- @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"])
- end
-
- it "should search provides if no package is available - if no match in installed provides then load the complete set" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
- expect(@yum_cache).to receive(:packages_from_require).twice.and_return([])
- expect(@yum_cache).to receive(:reload_provides)
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@new_resource.version).to eq(nil)
- end
-
- it "should search provides if no package is available and not load the complete set if action is :remove or :purge" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@yum_cache).to receive(:packages_from_require).once.and_return([])
- expect(@yum_cache).not_to receive(:reload_provides)
- @new_resource.action(:remove)
- @provider.load_current_resource
- expect(@yum_cache).to receive(:packages_from_require).once.and_return([])
- expect(@yum_cache).not_to receive(:reload_provides)
- @new_resource.action(:purge)
- @provider.load_current_resource
- end
-
- it "should search provides if no package is available - if no match in provides leave the name intact" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_provides => true,
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5",
- :package_available? => false,
- :version_available? => true,
- :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")
- expect(@yum_cache).to receive(:packages_from_require).twice.and_return([])
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@new_resource.package_name).to eq("cups")
- end
- end
-
- describe "when installing a package" do
- it "should run yum install with the package name and version" do
- @provider.load_current_resource
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5"
- )
- @provider.install_package("cups", "1.2.4-11.19.el5")
- end
-
- it "should run yum localinstall if given a path to an rpm" do
- @new_resource.source("/tmp/emacs-21.4-20.el5.i386.rpm")
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y localinstall /tmp/emacs-21.4-20.el5.i386.rpm"
- )
- @provider.install_package("emacs", "21.4-20.el5")
- end
-
- it "should run yum localinstall if given a path to an rpm as the package" do
- @new_resource = Chef::Resource::YumPackage.new("/tmp/emacs-21.4-20.el5.i386.rpm")
- allow(::File).to receive(:exist?).with("/tmp/emacs-21.4-20.el5.i386.rpm").and_return(true)
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect(@new_resource.source).to eq("/tmp/emacs-21.4-20.el5.i386.rpm")
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y localinstall /tmp/emacs-21.4-20.el5.i386.rpm"
- )
- @provider.install_package("/tmp/emacs-21.4-20.el5.i386.rpm", "21.4-20.el5")
- end
-
- it "should run yum install with the package name, version and arch" do
- @new_resource.arch("i386")
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- @provider.load_current_resource
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5.i386"
- )
- @provider.install_package("cups", "1.2.4-11.19.el5")
- end
-
- it "installs the package with the options given in the resource" do
- @provider.load_current_resource
- allow(@provider).to receive(:candidate_version).and_return("11")
- @new_resource.options("--disablerepo epmd")
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y --disablerepo epmd install cups-11"
- )
- @provider.install_package(@new_resource.name, @provider.candidate_version)
- end
-
- it "should raise an exception if the package is not available" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_from_cache => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.18.el5_2.3",
- :package_available? => true,
- :version_available? => nil,
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- expect { @provider.install_package("lolcats", "0.99") }.to raise_error(Chef::Exceptions::Package, %r{Version .* not found})
- end
-
- it "should raise an exception if candidate version is older than the installed version and allow_downgrade is false" do
- @new_resource.allow_downgrade(false)
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.15.el5",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [ "kernel" ],
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect { @provider.install_package("cups", "1.2.4-11.15.el5") }.to raise_error(Chef::Exceptions::Package, %r{is newer than candidate package})
- end
-
- it "should not raise an exception if candidate version is older than the installed version and the package is list in yum's installonlypkg option" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.15.el5",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [ "cups" ],
- :package_repository => "base",
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.15.el5"
- )
- @provider.install_package("cups", "1.2.4-11.15.el5")
- end
-
- it "should run yum downgrade if candidate version is older than the installed version and allow_downgrade is true" do
- @new_resource.allow_downgrade(true)
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.15.el5",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [],
- :package_repository => "base",
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y downgrade cups-1.2.4-11.15.el5"
- )
- @provider.install_package("cups", "1.2.4-11.15.el5")
- end
-
- it "should run yum install then flush the cache if :after is true" do
- @new_resource.flush_cache({ :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(
- "-d0 -e0 -y install cups-1.2.4-11.15.el5"
- )
- expect(@yum_cache).to receive(:reload).once
- @provider.install_package("cups", "1.2.4-11.15.el5")
- end
-
- it "should run yum install then not flush the cache if :after is false" do
- @new_resource.flush_cache({ :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(
- "-d0 -e0 -y install cups-1.2.4-11.15.el5"
- )
- expect(@yum_cache).not_to receive(:reload)
- @provider.install_package("cups", "1.2.4-11.15.el5")
- end
- end
-
- describe "when upgrading a package" do
- it "should run yum install if the package is installed and a version is given" do
- @provider.load_current_resource
- allow(@provider).to receive(:candidate_version).and_return("11")
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-11"
- )
- @provider.upgrade_package(@new_resource.name, @provider.candidate_version)
- end
-
- it "should run yum install if the package is not installed" do
- @provider.load_current_resource
- @current_resource = Chef::Resource::YumPackage.new("cups")
- allow(@provider).to receive(:candidate_version).and_return("11")
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-11"
- )
- @provider.upgrade_package(@new_resource.name, @provider.candidate_version)
- end
-
- it "should raise an exception if candidate version is older than the installed version" do
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "1.2.4-11.18.el5",
- :candidate_version => "1.2.4-11.15.el5",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [ "kernel" ],
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @provider.load_current_resource
- expect { @provider.upgrade_package("cups", "1.2.4-11.15.el5") }.to raise_error(Chef::Exceptions::Package, %r{is newer than candidate package})
- end
-
- # Test our little workaround, some crossover into Chef::Provider::Package territory
- it "should call action_upgrade in the parent if the current resource version is nil" do
- allow(@yum_cache).to receive(:installed_version).and_return(nil)
- @current_resource = Chef::Resource::YumPackage.new("cups")
- allow(@provider).to receive(:candidate_version).and_return("11")
- expect(@provider).to receive(:upgrade_package).with(["cups"], ["11"])
- @provider.run_action(:upgrade)
- end
-
- it "should call action_upgrade in the parent if the candidate version is nil" do
- @provider.load_current_resource
- @current_resource = Chef::Resource::YumPackage.new("cups")
- allow(@provider).to receive(:candidate_version).and_return(nil)
- expect(@provider).not_to receive(:upgrade_package)
- @provider.run_action(:upgrade)
- end
-
- it "should call action_upgrade in the parent if the candidate is newer" do
- @provider.load_current_resource
- @current_resource = Chef::Resource::YumPackage.new("cups")
- allow(@provider).to receive(:candidate_version).and_return("11")
- expect(@provider).to receive(:upgrade_package).with(["cups"], ["11"])
- @provider.run_action(:upgrade)
- end
-
- it "should not call action_upgrade in the parent if the candidate is older" do
- allow(@yum_cache).to receive(:installed_version).and_return("12")
- @provider.load_current_resource
- @current_resource = Chef::Resource::YumPackage.new("cups")
- allow(@provider).to receive(:candidate_version).and_return("11")
- expect(@provider).not_to receive(:upgrade_package)
- @provider.run_action(:upgrade)
- end
- end
-
- describe "when removing a package" do
- it "should run yum remove with the package name" do
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y remove emacs-1.0"
- )
- @provider.remove_package("emacs", "1.0")
- end
-
- it "should run yum remove with the package name and arch" do
- @new_resource.arch("x86_64")
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y remove emacs-1.0.x86_64"
- )
- @provider.remove_package("emacs", "1.0")
- end
- end
-
- describe "when purging a package" do
- it "should run yum remove with the package name" do
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y remove emacs-1.0"
- )
- @provider.purge_package("emacs", "1.0")
- end
- end
-
- describe "when locking a package" do
- it "should run yum versionlock add with the package name" do
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y versionlock add emacs"
- )
- @provider.lock_package("emacs", nil)
- end
- end
-
- describe "when unlocking a package" do
- it "should run yum versionlock delete with the package name" do
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y versionlock delete emacs"
- )
- @provider.unlock_package("emacs", nil)
- end
- end
-
- describe "when running yum" do
- it "should run yum once if it exits with a return code of 0" do
- @status = double("Status", :exitstatus => 0, :stdout => "", :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] }
- )
- @provider.send(:yum_command, "-d0 -e0 -y install emacs-1.0")
- end
-
- it "should run yum once if it exits with a return code > 0 and no scriptlet failures" do
- @status = double("Status", :exitstatus => 2, :stdout => "failure failure", :stderr => "problem problem")
- 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] }
- )
- expect { @provider.send(: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 => "")
- 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] }
- )
- # will still raise an exception, can't stub out the subsequent call
- expect { @provider.send(:yum_command, "-d0 -e0 -y install emacs-1.0") }.to raise_error(Chef::Exceptions::Exec)
- end
-
- 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 => "")
- 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] }
- )
- # will still raise an exception, can't stub out the subsequent call
- expect { @provider.send(:yum_command, "-d0 -e0 -y install emacs-1.0") }.to raise_error(Chef::Exceptions::Exec)
- end
-
- it "should pass the yum_binary to the command if its specified" do
- @new_resource.yum_binary "yum-deprecated"
- expect(@yum_cache).to receive(:yum_binary=).with("yum-deprecated")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @status = double("Status", :exitstatus => 0, :stdout => "", :stderr => "")
- 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] }
- )
- @provider.send(:yum_command, "-d0 -e0 -y install emacs-1.0")
- end
- end
-end
-
-describe Chef::Provider::Package::Yum::RPMUtils do
- describe "version_parse" do
- before do
- @rpmutils = Chef::Provider::Package::Yum::RPMUtils
- end
-
- it "parses known good epoch strings" do
- [
- [ "0:3.3", [ 0, "3.3", nil ] ],
- [ "9:1.7.3", [ 9, "1.7.3", nil ] ],
- [ "15:20020927", [ 15, "20020927", nil ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
-
- it "parses strange epoch strings" do
- [
- [ ":3.3", [ 0, "3.3", nil ] ],
- [ "-1:1.7.3", [ nil, nil, "1:1.7.3" ] ],
- [ "-:20020927", [ nil, nil, ":20020927" ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
-
- it "parses known good version strings" do
- [
- [ "3.3", [ nil, "3.3", nil ] ],
- [ "1.7.3", [ nil, "1.7.3", nil ] ],
- [ "20020927", [ nil, "20020927", nil ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
-
- it "parses strange version strings" do
- [
- [ "3..3", [ nil, "3..3", nil ] ],
- [ "0001.7.3", [ nil, "0001.7.3", nil ] ],
- [ "20020927,3", [ nil, "20020927,3", nil ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
-
- it "parses known good version release strings" do
- [
- [ "3.3-0.pre3.1.60.el5_5.1", [ nil, "3.3", "0.pre3.1.60.el5_5.1" ] ],
- [ "1.7.3-1jpp.2.el5", [ nil, "1.7.3", "1jpp.2.el5" ] ],
- [ "20020927-46.el5", [ nil, "20020927", "46.el5" ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
-
- it "parses strange version release strings" do
- [
- [ "3.3-", [ nil, "3.3", nil ] ],
- [ "-1jpp.2.el5", [ nil, nil, "1jpp.2.el5" ] ],
- [ "-0020020927-46.el5", [ nil, "-0020020927", "46.el5" ] ],
- ].each do |x, y|
- expect(@rpmutils.version_parse(x)).to eq(y)
- end
- end
- end
-
- describe "rpmvercmp" do
- before do
- @rpmutils = Chef::Provider::Package::Yum::RPMUtils
- end
-
- it "should validate version compare logic for standard examples" do
- [
- # numeric
- [ "0.0.2", "0.0.1", 1 ],
- [ "0.2.0", "0.1.0", 1 ],
- [ "2.0.0", "1.0.0", 1 ],
- [ "0.0.1", "0.0.1", 0 ],
- [ "0.0.1", "0.0.2", -1 ],
- [ "0.1.0", "0.2.0", -1 ],
- [ "1.0.0", "2.0.0", -1 ],
- # alpha
- [ "bb", "aa", 1 ],
- [ "ab", "aa", 1 ],
- [ "aa", "aa", 0 ],
- [ "aa", "bb", -1 ],
- [ "aa", "ab", -1 ],
- [ "BB", "AA", 1 ],
- [ "AA", "AA", 0 ],
- [ "AA", "BB", -1 ],
- [ "aa", "AA", 1 ],
- [ "AA", "aa", -1 ],
- # alphanumeric
- [ "0.0.1b", "0.0.1a", 1 ],
- [ "0.1b.0", "0.1a.0", 1 ],
- [ "1b.0.0", "1a.0.0", 1 ],
- [ "0.0.1a", "0.0.1a", 0 ],
- [ "0.0.1a", "0.0.1b", -1 ],
- [ "0.1a.0", "0.1b.0", -1 ],
- [ "1a.0.0", "1b.0.0", -1 ],
- # alphanumeric against alphanumeric
- [ "0.0.1", "0.0.a", 1 ],
- [ "0.1.0", "0.a.0", 1 ],
- [ "1.0.0", "a.0.0", 1 ],
- [ "0.0.a", "0.0.a", 0 ],
- [ "0.0.a", "0.0.1", -1 ],
- [ "0.a.0", "0.1.0", -1 ],
- [ "a.0.0", "1.0.0", -1 ],
- # alphanumeric against numeric
- [ "0.0.2", "0.0.1a", 1 ],
- [ "0.0.2a", "0.0.1", 1 ],
- [ "0.0.1", "0.0.2a", -1 ],
- [ "0.0.1a", "0.0.2", -1 ],
- # length
- [ "0.0.1aa", "0.0.1a", 1 ],
- [ "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)
- end
- end
-
- it "should validate version compare logic for strange examples" do
- [
- [ "2,0,0", "1.0.0", 1 ],
- [ "0.0.1", "0,0.1", 0 ],
- [ "1.0.0", "2,0,0", -1 ],
- [ "002.0.0", "001.0.0", 1 ],
- [ "001..0.1", "001..0.0", 1 ],
- [ "-001..1", "-001..0", 1 ],
- [ "1.0.1", nil, 1 ],
- [ nil, nil, 0 ],
- [ nil, "1.0.1", -1 ],
- [ "1.0.1", "", 1 ],
- [ "", "", 0 ],
- [ "", "1.0.1", -1 ],
- ].each do |x, y, result|
- expect(@rpmutils.rpmvercmp(x, y)).to eq(result)
- end
- end
-
- it "tests isalnum good input" do
- %w{a z A Z 0 9}.each do |t|
- expect(@rpmutils.isalnum(t)).to eq(true)
- end
- end
-
- it "tests isalnum bad input" do
- [ "-", ".", "!", "^", ":", "_" ].each do |t|
- expect(@rpmutils.isalnum(t)).to eq(false)
- end
- end
-
- it "tests isalpha good input" do
- %w{a z A Z}.each do |t|
- expect(@rpmutils.isalpha(t)).to eq(true)
- end
- end
-
- it "tests isalpha bad input" do
- [ "0", "9", "-", ".", "!", "^", ":", "_" ].each do |t|
- expect(@rpmutils.isalpha(t)).to eq(false)
- end
- end
-
- it "tests isdigit good input" do
- %w{0 9}.each do |t|
- expect(@rpmutils.isdigit(t)).to eq(true)
- end
- end
-
- it "tests isdigit bad input" do
- [ "A", "z", "-", ".", "!", "^", ":", "_" ].each do |t|
- expect(@rpmutils.isdigit(t)).to eq(false)
- end
- end
- end
-
-end
-
-describe Chef::Provider::Package::Yum::RPMVersion do
- describe "new - with parsing" do
- before do
- @rpmv = Chef::Provider::Package::Yum::RPMVersion.new("1:1.6.5-9.36.el5")
- end
-
- it "should expose evr (name-version-release) available" do
- expect(@rpmv.e).to eq(1)
- expect(@rpmv.v).to eq("1.6.5")
- expect(@rpmv.r).to eq("9.36.el5")
-
- expect(@rpmv.evr).to eq("1:1.6.5-9.36.el5")
- end
-
- it "should output a version-release string" do
- expect(@rpmv.to_s).to eq("1.6.5-9.36.el5")
- end
- end
-
- describe "new - no parsing" do
- before do
- @rpmv = Chef::Provider::Package::Yum::RPMVersion.new("1", "1.6.5", "9.36.el5")
- end
-
- it "should expose evr (name-version-release) available" do
- expect(@rpmv.e).to eq(1)
- expect(@rpmv.v).to eq("1.6.5")
- expect(@rpmv.r).to eq("9.36.el5")
-
- expect(@rpmv.evr).to eq("1:1.6.5-9.36.el5")
- end
-
- it "should output a version-release string" do
- expect(@rpmv.to_s).to eq("1.6.5-9.36.el5")
- end
- end
-
- it "should raise an error unless passed 1 or 3 args" do
- expect do
- Chef::Provider::Package::Yum::RPMVersion.new()
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMVersion.new("1:1.6.5-9.36.el5")
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMVersion.new("1:1.6.5-9.36.el5", "extra")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMVersion.new("1", "1.6.5", "9.36.el5")
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMVersion.new("1", "1.6.5", "9.36.el5", "extra")
- end.to raise_error(ArgumentError)
- end
-
- # thanks version_class_spec.rb!
- describe "compare" do
- it "should sort based on complete epoch-version-release data" do
- [
- # smaller, larger
- [ "0:1.6.5-9.36.el5",
- "1:1.6.5-9.36.el5" ],
- [ "0:2.3-15.el5",
- "0:3.3-15.el5" ],
- [ "0:alpha9.8-27.2",
- "0:beta9.8-27.2" ],
- [ "0:0.09-14jpp.3",
- "0:0.09-15jpp.3" ],
- [ "0:0.9.0-0.6.20110211.el5",
- "0:0.9.0-0.6.20120211.el5" ],
- [ "0:1.9.1-4.el5",
- "0:1.9.1-5.el5" ],
- [ "0:1.4.10-7.20090624svn.el5",
- "0:1.4.10-7.20090625svn.el5" ],
- [ "0:2.3.4-2.el5",
- "0:2.3.4-2.el6" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm).to be < lg
- expect(lg).to be > sm
- expect(sm).not_to eq(lg)
- end
- end
-
- it "should sort based on partial epoch-version-release data" do
- [
- # smaller, larger
- [ ":1.6.5-9.36.el5",
- "1:1.6.5-9.36.el5" ],
- [ "2.3-15.el5",
- "3.3-15.el5" ],
- [ "alpha9.8",
- "beta9.8" ],
- %w{14jpp
-15jpp},
- [ "0.9.0-0.6",
- "0.9.0-0.7" ],
- [ "0:1.9",
- "3:1.9" ],
- [ "2.3-2.el5",
- "2.3-2.el6" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm).to be < lg
- expect(lg).to be > sm
- expect(sm).not_to eq(lg)
- end
- end
-
- it "should verify equality of complete epoch-version-release data" do
- [
- [ "0:1.6.5-9.36.el5",
- "0:1.6.5-9.36.el5" ],
- [ "0:2.3-15.el5",
- "0:2.3-15.el5" ],
- [ "0:alpha9.8-27.2",
- "0:alpha9.8-27.2" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm).to eq(lg)
- end
- end
-
- it "should verify equality of partial epoch-version-release data" do
- [
- [ ":1.6.5-9.36.el5",
- "0:1.6.5-9.36.el5" ],
- [ "2.3-15.el5",
- "2.3-15.el5" ],
- [ "alpha9.8-3",
- "alpha9.8-3" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm).to eq(lg)
- end
- end
- end
-
- describe "partial compare" do
- it "should compare based on partial epoch-version-release data" do
- [
- # smaller, larger
- [ "0:1.1.1-1",
- "1:" ],
- [ "0:1.1.1-1",
- "0:1.1.2" ],
- [ "0:1.1.1-1",
- "0:1.1.2-1" ],
- [ "0:",
- "1:1.1.1-1" ],
- [ "0:1.1.1",
- "0:1.1.2-1" ],
- [ "0:1.1.1-1",
- "0:1.1.2-1" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm.partial_compare(lg)).to eq(-1)
- expect(lg.partial_compare(sm)).to eq(1)
- expect(sm.partial_compare(lg)).not_to eq(0)
- end
- end
-
- it "should verify equality based on partial epoch-version-release data" do
- [
- [ "0:",
- "0:1.1.1-1" ],
- [ "0:1.1.1",
- "0:1.1.1-1" ],
- [ "0:1.1.1-1",
- "0:1.1.1-1" ],
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMVersion.new(smaller)
- lg = Chef::Provider::Package::Yum::RPMVersion.new(larger)
- expect(sm.partial_compare(lg)).to eq(0)
- end
- end
- end
-
-end
-
-describe Chef::Provider::Package::Yum::RPMPackage do
- describe "new - with parsing" do
- before do
- @rpm = Chef::Provider::Package::Yum::RPMPackage.new("testing", "1:1.6.5-9.36.el5", "x86_64", [])
- end
-
- it "should expose nevra (name-epoch-version-release-arch) available" do
- expect(@rpm.name).to eq("testing")
- expect(@rpm.version.e).to eq(1)
- expect(@rpm.version.v).to eq("1.6.5")
- expect(@rpm.version.r).to eq("9.36.el5")
- expect(@rpm.arch).to eq("x86_64")
-
- expect(@rpm.nevra).to eq("testing-1:1.6.5-9.36.el5.x86_64")
- expect(@rpm.to_s).to eq(@rpm.nevra)
- end
-
- it "should always have at least one provide, itself" do
- expect(@rpm.provides.size).to eq(1)
- expect(@rpm.provides[0].name).to eql("testing")
- expect(@rpm.provides[0].version.evr).to eql("1:1.6.5-9.36.el5")
- expect(@rpm.provides[0].flag).to eql(:==)
- end
- end
-
- describe "new - no parsing" do
- before do
- @rpm = Chef::Provider::Package::Yum::RPMPackage.new("testing", "1", "1.6.5", "9.36.el5", "x86_64", [])
- end
-
- it "should expose nevra (name-epoch-version-release-arch) available" do
- expect(@rpm.name).to eq("testing")
- expect(@rpm.version.e).to eq(1)
- expect(@rpm.version.v).to eq("1.6.5")
- expect(@rpm.version.r).to eq("9.36.el5")
- expect(@rpm.arch).to eq("x86_64")
-
- expect(@rpm.nevra).to eq("testing-1:1.6.5-9.36.el5.x86_64")
- expect(@rpm.to_s).to eq(@rpm.nevra)
- end
-
- it "should always have at least one provide, itself" do
- expect(@rpm.provides.size).to eq(1)
- expect(@rpm.provides[0].name).to eql("testing")
- expect(@rpm.provides[0].version.evr).to eql("1:1.6.5-9.36.el5")
- expect(@rpm.provides[0].flag).to eql(:==)
- end
- end
-
- it "should raise an error unless passed 4 or 6 args" do
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new()
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1:1.6.5-9.36.el5")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1:1.6.5-9.36.el5", "x86_64")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1:1.6.5-9.36.el5", "x86_64", [])
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1", "1.6.5", "9.36.el5", "x86_64")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1", "1.6.5", "9.36.el5", "x86_64", [])
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMPackage.new("testing", "1", "1.6.5", "9.36.el5", "x86_64", [], "extra")
- end.to raise_error(ArgumentError)
- end
-
- describe "<=>" do
- it "should sort alphabetically based on package name" do
- [
- [ "a-test",
- "b-test" ],
- [ "B-test",
- "a-test" ],
- [ "A-test",
- "B-test" ],
- [ "Aa-test",
- "aA-test" ],
- %w{1test
-2test},
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMPackage.new(smaller, "0:0.0.1-1", "x86_64", [])
- lg = Chef::Provider::Package::Yum::RPMPackage.new(larger, "0:0.0.1-1", "x86_64", [])
- expect(sm).to be < lg
- expect(lg).to be > sm
- expect(sm).not_to eq(lg)
- end
- end
-
- it "should sort alphabetically based on package arch" do
- [
- %w{i386
-x86_64},
- %w{i386
-noarch},
- %w{noarch
-x86_64},
- ].each do |smaller, larger|
- sm = Chef::Provider::Package::Yum::RPMPackage.new("test-package", "0:0.0.1-1", smaller, [])
- lg = Chef::Provider::Package::Yum::RPMPackage.new("test-package", "0:0.0.1-1", larger, [])
- expect(sm).to be < lg
- expect(lg).to be > sm
- expect(sm).not_to eq(lg)
- end
- end
- end
-
-end
-
-describe Chef::Provider::Package::Yum::RPMDbPackage do
- before(:each) do
- # name, version, arch, installed, available, repoid
- @rpm_x = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "0:1.6.5-9.36.el5", "noarch", [], false, true, "base")
- @rpm_y = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "0:1.6.5-9.36.el5", "noarch", [], true, true, "extras")
- @rpm_z = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "0:1.6.5-9.36.el5", "noarch", [], true, false, "other")
- end
-
- describe "initialize" do
- it "should return a Chef::Provider::Package::Yum::RPMDbPackage object" do
- expect(@rpm_x).to be_kind_of(Chef::Provider::Package::Yum::RPMDbPackage)
- end
- end
-
- describe "available" do
- it "should return true" do
- expect(@rpm_x.available).to eq(true)
- expect(@rpm_y.available).to eq(true)
- expect(@rpm_z.available).to eq(false)
- end
- end
-
- describe "installed" do
- it "should return true" do
- expect(@rpm_x.installed).to eq(false)
- expect(@rpm_y.installed).to eq(true)
- expect(@rpm_z.installed).to eq(true)
- end
- end
-
- describe "repoid" do
- it "should return the source repository repoid" do
- expect(@rpm_x.repoid).to eq("base")
- expect(@rpm_y.repoid).to eq("extras")
- expect(@rpm_z.repoid).to eq("other")
- end
- end
-end
-
-describe Chef::Provider::Package::Yum::RPMDependency do
- describe "new - with parsing" do
- before do
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :==)
- end
-
- it "should expose name, version, flag available" do
- expect(@rpmdep.name).to eq("testing")
- expect(@rpmdep.version.e).to eq(1)
- expect(@rpmdep.version.v).to eq("1.6.5")
- expect(@rpmdep.version.r).to eq("9.36.el5")
- expect(@rpmdep.flag).to eq(:==)
- end
- end
-
- describe "new - no parsing" do
- before do
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1", "1.6.5", "9.36.el5", :==)
- end
-
- it "should expose name, version, flag available" do
- expect(@rpmdep.name).to eq("testing")
- expect(@rpmdep.version.e).to eq(1)
- expect(@rpmdep.version.v).to eq("1.6.5")
- expect(@rpmdep.version.r).to eq("9.36.el5")
- expect(@rpmdep.flag).to eq(:==)
- end
- end
-
- it "should raise an error unless passed 3 or 5 args" do
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new()
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :==)
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :==, "extra")
- end.to raise_error(ArgumentError)
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing", "1", "1.6.5", "9.36.el5", :==)
- end.not_to raise_error
- expect do
- Chef::Provider::Package::Yum::RPMDependency.new("testing", "1", "1.6.5", "9.36.el5", :==, "extra")
- end.to raise_error(ArgumentError)
- end
-
- describe "parse" do
- it "should parse a name, flag, version string into a valid RPMDependency object" do
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.parse("testing >= 1:1.6.5-9.36.el5")
-
- expect(@rpmdep.name).to eq("testing")
- expect(@rpmdep.version.e).to eq(1)
- expect(@rpmdep.version.v).to eq("1.6.5")
- expect(@rpmdep.version.r).to eq("9.36.el5")
- expect(@rpmdep.flag).to eq(:>=)
- end
-
- it "should parse a name into a valid RPMDependency object" do
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.parse("testing")
-
- expect(@rpmdep.name).to eq("testing")
- expect(@rpmdep.version.e).to eq(nil)
- expect(@rpmdep.version.v).to eq(nil)
- expect(@rpmdep.version.r).to eq(nil)
- expect(@rpmdep.flag).to eq(:==)
- end
-
- it "should parse an invalid string into the name of a RPMDependency object" do
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.parse("testing blah >")
-
- expect(@rpmdep.name).to eq("testing blah >")
- expect(@rpmdep.version.e).to eq(nil)
- expect(@rpmdep.version.v).to eq(nil)
- expect(@rpmdep.version.r).to eq(nil)
- expect(@rpmdep.flag).to eq(:==)
- end
-
- it "should parse various valid flags" do
- [
- [ ">", :> ],
- [ ">=", :>= ],
- [ "=", :== ],
- [ "==", :== ],
- [ "<=", :<= ],
- [ "<", :< ],
- ].each do |before, after|
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.parse("testing #{before} 1:1.1-1")
- expect(@rpmdep.flag).to eq(after)
- end
- end
-
- it "should parse various invalid flags and treat them as names" do
- [
- [ "<>", :== ],
- [ "!=", :== ],
- [ ">>", :== ],
- [ "<<", :== ],
- [ "!", :== ],
- [ "~", :== ],
- ].each do |before, after|
- @rpmdep = Chef::Provider::Package::Yum::RPMDependency.parse("testing #{before} 1:1.1-1")
- expect(@rpmdep.name).to eq("testing #{before} 1:1.1-1")
- expect(@rpmdep.flag).to eq(after)
- end
- end
- end
-
- describe "satisfy?" do
- it "should raise an error unless a RPMDependency is passed" do
- @rpmprovide = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :==)
- @rpmrequire = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :>=)
- expect do
- @rpmprovide.satisfy?("hi")
- end.to raise_error(ArgumentError)
- expect do
- @rpmprovide.satisfy?(@rpmrequire)
- end.not_to raise_error
- end
-
- it "should validate dependency satisfaction logic for standard examples" do
- [
- # names
- [ "test", "test", true ],
- [ "test", "foo", false ],
- # full: epoch:version-relese
- [ "testing = 1:1.1-1", "testing > 1:1.1-0", true ],
- [ "testing = 1:1.1-1", "testing >= 1:1.1-0", true ],
- [ "testing = 1:1.1-1", "testing >= 1:1.1-1", true ],
- [ "testing = 1:1.1-1", "testing = 1:1.1-1", true ],
- [ "testing = 1:1.1-1", "testing == 1:1.1-1", true ],
- [ "testing = 1:1.1-1", "testing <= 1:1.1-1", true ],
- [ "testing = 1:1.1-1", "testing <= 1:1.1-0", false ],
- [ "testing = 1:1.1-1", "testing < 1:1.1-0", false ],
- # partial: epoch:version
- [ "testing = 1:1.1", "testing > 1:1.0", true ],
- [ "testing = 1:1.1", "testing >= 1:1.0", true ],
- [ "testing = 1:1.1", "testing >= 1:1.1", true ],
- [ "testing = 1:1.1", "testing = 1:1.1", true ],
- [ "testing = 1:1.1", "testing == 1:1.1", true ],
- [ "testing = 1:1.1", "testing <= 1:1.1", true ],
- [ "testing = 1:1.1", "testing <= 1:1.0", false ],
- [ "testing = 1:1.1", "testing < 1:1.0", false ],
- # partial: epoch
- [ "testing = 1:", "testing > 0:", true ],
- [ "testing = 1:", "testing >= 0:", true ],
- [ "testing = 1:", "testing >= 1:", true ],
- [ "testing = 1:", "testing = 1:", true ],
- [ "testing = 1:", "testing == 1:", true ],
- [ "testing = 1:", "testing <= 1:", true ],
- [ "testing = 1:", "testing <= 0:", false ],
- [ "testing = 1:", "testing < 0:", false ],
- # mix and match!
- [ "testing = 1:1.1-1", "testing == 1:1.1", true ],
- [ "testing = 1:1.1-1", "testing == 1:", true ],
- ].each do |prov, req, result|
- @rpmprovide = Chef::Provider::Package::Yum::RPMDependency.parse(prov)
- @rpmrequire = Chef::Provider::Package::Yum::RPMDependency.parse(req)
-
- expect(@rpmprovide.satisfy?(@rpmrequire)).to eq(result)
- expect(@rpmrequire.satisfy?(@rpmprovide)).to eq(result)
- end
- end
- end
-
-end
-
-# thanks resource_collection_spec.rb!
-describe Chef::Provider::Package::Yum::RPMDb do
- before(:each) do
- @rpmdb = Chef::Provider::Package::Yum::RPMDb.new
- # name, version, arch, installed, available
- deps_v = [
- Chef::Provider::Package::Yum::RPMDependency.parse("libz.so.1()(64bit)"),
- Chef::Provider::Package::Yum::RPMDependency.parse("test-package-a = 0:1.6.5-9.36.el5"),
- ]
- deps_z = [
- Chef::Provider::Package::Yum::RPMDependency.parse("libz.so.1()(64bit)"),
- Chef::Provider::Package::Yum::RPMDependency.parse("config(test) = 0:1.6.5-9.36.el5"),
- Chef::Provider::Package::Yum::RPMDependency.parse("test-package-c = 0:1.6.5-9.36.el5"),
- ]
- @rpm_v = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-a", "0:1.6.5-9.36.el5", "i386", deps_v, true, false, "base")
- @rpm_w = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "0:1.6.5-9.36.el5", "i386", [], true, true, "extras")
- @rpm_x = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "0:1.6.5-9.36.el5", "x86_64", [], false, true, "extras")
- @rpm_y = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-b", "1:1.6.5-9.36.el5", "x86_64", [], true, true, "extras")
- @rpm_z = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-c", "0:1.6.5-9.36.el5", "noarch", deps_z, true, true, "base")
- @rpm_z_mirror = Chef::Provider::Package::Yum::RPMDbPackage.new("test-package-c", "0:1.6.5-9.36.el5", "noarch", deps_z, true, true, "base")
- end
-
- describe "initialize" do
- it "should return a Chef::Provider::Package::Yum::RPMDb object" do
- expect(@rpmdb).to be_kind_of(Chef::Provider::Package::Yum::RPMDb)
- end
- end
-
- describe "push" do
- it "should accept an RPMDbPackage object through pushing" do
- expect { @rpmdb.push(@rpm_w) }.not_to raise_error
- end
-
- it "should accept multiple RPMDbPackage object through pushing" do
- expect { @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z) }.not_to raise_error
- end
-
- it "should only accept an RPMDbPackage object" do
- expect { @rpmdb.push("string") }.to raise_error(ArgumentError)
- end
-
- it "should add the package to the package db" do
- @rpmdb.push(@rpm_w)
- expect(@rpmdb["test-package-b"]).not_to eq(nil)
- end
-
- it "should add conditionally add the package to the available list" do
- expect(@rpmdb.available_size).to eq(0)
- @rpmdb.push(@rpm_v, @rpm_w)
- expect(@rpmdb.available_size).to eq(1)
- end
-
- it "should add conditionally add the package to the installed list" do
- expect(@rpmdb.installed_size).to eq(0)
- @rpmdb.push(@rpm_w, @rpm_x)
- expect(@rpmdb.installed_size).to eq(1)
- end
-
- it "should have a total of 2 packages in the RPMDb" do
- expect(@rpmdb.size).to eq(0)
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb.size).to eq(2)
- end
-
- it "should keep the Array unique when a duplicate is pushed" do
- @rpmdb.push(@rpm_z, @rpm_z_mirror)
- expect(@rpmdb["test-package-c"].size).to eq(1)
- end
-
- it "should register the package provides in the provides index" do
- @rpmdb.push(@rpm_v, @rpm_w, @rpm_z)
- expect(@rpmdb.lookup_provides("test-package-a")[0]).to eq(@rpm_v)
- expect(@rpmdb.lookup_provides("config(test)")[0]).to eq(@rpm_z)
- expect(@rpmdb.lookup_provides("libz.so.1()(64bit)")[0]).to eq(@rpm_v)
- expect(@rpmdb.lookup_provides("libz.so.1()(64bit)")[1]).to eq(@rpm_z)
- end
- end
-
- describe "<<" do
- it "should accept an RPMPackage object through the << operator" do
- expect { @rpmdb << @rpm_w }.not_to raise_error
- end
- end
-
- describe "lookup" do
- it "should return an Array of RPMPackage objects by index" do
- @rpmdb << @rpm_w
- expect(@rpmdb.lookup("test-package-b")).to be_kind_of(Array)
- end
- end
-
- describe "[]" do
- it "should return an Array of RPMPackage objects though the [index] operator" do
- @rpmdb << @rpm_w
- expect(@rpmdb["test-package-b"]).to be_kind_of(Array)
- end
-
- it "should return an Array of 3 RPMPackage objects" do
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb["test-package-b"].size).to eq(3)
- end
-
- it "should return an Array of RPMPackage objects sorted from newest to oldest" do
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb["test-package-b"][0]).to eq(@rpm_y)
- expect(@rpmdb["test-package-b"][1]).to eq(@rpm_x)
- expect(@rpmdb["test-package-b"][2]).to eq(@rpm_w)
- end
- end
-
- describe "lookup_provides" do
- it "should return an Array of RPMPackage objects by index" do
- @rpmdb << @rpm_z
- x = @rpmdb.lookup_provides("config(test)")
- expect(x).to be_kind_of(Array)
- expect(x[0]).to eq(@rpm_z)
- end
- end
-
- describe "clear" do
- it "should clear the RPMDb" do
- expect(@rpmdb).to receive(:clear_available).once
- expect(@rpmdb).to receive(:clear_installed).once
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb.size).not_to eq(0)
- expect(@rpmdb.lookup_provides("config(test)")).to be_kind_of(Array)
- @rpmdb.clear
- expect(@rpmdb.lookup_provides("config(test)")).to eq(nil)
- expect(@rpmdb.size).to eq(0)
- end
- end
-
- describe "clear_available" do
- it "should clear the available list" do
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb.available_size).not_to eq(0)
- @rpmdb.clear_available
- expect(@rpmdb.available_size).to eq(0)
- end
- end
-
- describe "available?" do
- it "should return true if a package is available" do
- expect(@rpmdb.available?(@rpm_w)).to eq(false)
- @rpmdb.push(@rpm_v, @rpm_w)
- expect(@rpmdb.available?(@rpm_v)).to eq(false)
- expect(@rpmdb.available?(@rpm_w)).to eq(true)
- end
- end
-
- describe "clear_installed" do
- it "should clear the installed list" do
- @rpmdb.push(@rpm_w, @rpm_x, @rpm_y, @rpm_z)
- expect(@rpmdb.installed_size).not_to eq(0)
- @rpmdb.clear_installed
- expect(@rpmdb.installed_size).to eq(0)
- end
- end
-
- describe "installed?" do
- it "should return true if a package is installed" do
- expect(@rpmdb.installed?(@rpm_w)).to eq(false)
- @rpmdb.push(@rpm_w, @rpm_x)
- expect(@rpmdb.installed?(@rpm_w)).to eq(true)
- expect(@rpmdb.installed?(@rpm_x)).to eq(false)
- end
- end
-
- describe "whatprovides" do
- it "should raise an error unless a RPMDependency is passed" do
- @rpmprovide = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :==)
- @rpmrequire = Chef::Provider::Package::Yum::RPMDependency.new("testing", "1:1.6.5-9.36.el5", :>=)
- expect do
- @rpmdb.whatprovides("hi")
- end.to raise_error(ArgumentError)
- expect do
- @rpmdb.whatprovides(@rpmrequire)
- end.not_to raise_error
- end
-
- it "should return an Array of packages statisfying a RPMDependency" do
- @rpmdb.push(@rpm_v, @rpm_w, @rpm_z)
-
- @rpmrequire = Chef::Provider::Package::Yum::RPMDependency.parse("test-package-a >= 1.6.5")
- x = @rpmdb.whatprovides(@rpmrequire)
- expect(x).to be_kind_of(Array)
- expect(x[0]).to eq(@rpm_v)
-
- @rpmrequire = Chef::Provider::Package::Yum::RPMDependency.parse("libz.so.1()(64bit)")
- x = @rpmdb.whatprovides(@rpmrequire)
- expect(x).to be_kind_of(Array)
- expect(x[0]).to eq(@rpm_v)
- expect(x[1]).to eq(@rpm_z)
- end
- end
-
-end
-
-describe Chef::Provider::Package::Yum::YumCache do
- # allow for the reset of a Singleton
- # thanks to Ian White (http://blog.ardes.com/2006/12/11/testing-singletons-with-ruby)
- class << Chef::Provider::Package::Yum::YumCache
- def reset_instance
- Singleton.send :__init__, self
- self
- end
- end
-
- let(:yum_exe) do
- StringIO.new("#!/usr/bin/python\n\naldsjfa\ldsajflkdsjf\lajsdfj")
- end
-
- let(:bin_exe) do
- StringIO.new(SecureRandom.random_bytes)
- end
-
- before(:each) do
- @stdin = double("STDIN", :nil_object => true)
- @stdout = double("STDOUT", :nil_object => true)
-
- @stdout_good = <<EOF
-[option installonlypkgs] kernel kernel-bigmem kernel-enterprise
-erlang-mochiweb 0 1.4.1 5.el5 x86_64 ['erlang-mochiweb = 1.4.1-5.el5', 'mochiweb = 1.4.1-5.el5'] i installed
-zip 0 2.31 2.el5 x86_64 ['zip = 2.31-2.el5'] r base
-zisofs-tools 0 1.0.6 3.2.2 x86_64 [] a extras
-zlib 0 1.2.3 3 x86_64 ['zlib = 1.2.3-3', 'libz.so.1()(64bit)'] r base
-zlib 0 1.2.3 3 i386 ['zlib = 1.2.3-3', 'libz.so.1'] r base
-zlib-devel 0 1.2.3 3 i386 [] a extras
-zlib-devel 0 1.2.3 3 x86_64 ['zlib-devel = 1.2.3-3'] r base
-znc 0 0.098 1.el5 x86_64 [] a base
-znc-devel 0 0.098 1.el5 i386 [] a extras
-znc-devel 0 0.098 1.el5 x86_64 [] a base
-znc-extra 0 0.098 1.el5 x86_64 [] a base
-znc-modtcl 0 0.098 1.el5 x86_64 [] a base
-znc-test.beta1 0 0.098 1.el5 x86_64 [] a extras
-znc-test.test.beta1 0 0.098 1.el5 x86_64 [] a base
-EOF
- @stdout_bad_type = <<EOF
-zip 0 2.31 2.el5 x86_64 ['zip = 2.31-2.el5'] r base
-zlib 0 1.2.3 3 x86_64 ['zlib = 1.2.3-3', 'libz.so.1()(64bit)'] c base
-zlib-devel 0 1.2.3 3 i386 [] a extras
-zlib-devel 0 1.2.3 3 x86_64 ['zlib-devel = 1.2.3-3'] bad installed
-znc-modtcl 0 0.098 1.el5 x86_64 [] a base
-EOF
-
- @stdout_bad_separators = <<EOF
-zip 0 2.31 2.el5 x86_64 ['zip = 2.31-2.el5'] r base
-zlib 0 1.2.3 3 x86_64 ['zlib = 1.2.3-3', 'libz.so.1()(64bit)'] i base bad
-zlib-devel 0 1.2.3 3 i386 [] a extras
-bad zlib-devel 0 1.2.3 3 x86_64 ['zlib-devel = 1.2.3-3'] i installed
-znc-modtcl 0 0.098 1.el5 x86_64 [] a base bad
-EOF
-
- @stdout_no_output = ""
-
- @stderr = <<EOF
-yum-dump Config Error: File contains no section headers.
-file: file://///etc/yum.repos.d/CentOS-Base.repo, line: 12
-'qeqwewe\n'
-EOF
- @status = double("Status", :exitstatus => 0, :stdin => @stdin, :stdout => @stdout_good, :stderr => @stderr)
- # new singleton each time
- Chef::Provider::Package::Yum::YumCache.reset_instance
- @yc = Chef::Provider::Package::Yum::YumCache.instance
- # load valid data
- @yc.yum_binary = "yum"
- allow(@yc).to receive(:shell_out!).and_return(@status)
- allow_any_instance_of(described_class).to receive(:which).with("yum").and_return("/usr/bin/yum")
- allow(::File).to receive(:open).with("/usr/bin/yum", "r") do |&block|
- res = block.call(yum_exe)
- # a bit of a hack. rewind this since it seem that no matter what
- # I do, we get the same StringIO objects on multiple calls to
- # ::File.open
- yum_exe.rewind; res
- end
- end
-
- describe "initialize" do
- it "should return a Chef::Provider::Package::Yum::YumCache object" do
- expect(@yc).to be_kind_of(Chef::Provider::Package::Yum::YumCache)
- end
-
- it "should register reload for start of Chef::Client runs" do
- Chef::Provider::Package::Yum::YumCache.reset_instance
- expect(Chef::Client).to receive(:when_run_starts) do |&b|
- expect(b).not_to be_nil
- end
- @yc = Chef::Provider::Package::Yum::YumCache.instance
- end
- end
-
- describe "python_bin" do
- it "should return the default python if an error occurs" do
- allow(::File).to receive(:open).with("/usr/bin/yum", "r").and_raise(StandardError)
- expect(@yc.python_bin).to eq("/usr/bin/python")
- 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 }
- 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 }
- 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 }
- expect(@yc.python_bin).to eq("/usr/bin/super_python")
- end
- end
-
- describe "refresh" do
- it "should implicitly call yum-dump.py only once by default after being instantiated" do
- expect(@yc).to receive(:shell_out!).once
- @yc.installed_version("zlib")
- @yc.reset
- @yc.installed_version("zlib")
- end
-
- 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])
- @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])
- @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])
- @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])
- @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])
- @yc.refresh
- end
-
- it "should warn about invalid data with too many separators" do
- @status = double("Status", :exitstatus => 0, :stdin => @stdin, :stdout => @stdout_bad_separators, :stderr => @stderr)
- allow(@yc).to receive(:shell_out!).and_return(@status)
- expect(Chef::Log).to receive(:warn).exactly(3).times.with(%r{Problem parsing})
- @yc.refresh
- end
-
- it "should warn about invalid data with an incorrect type" do
- @status = double("Status", :exitstatus => 0, :stdin => @stdin, :stdout => @stdout_bad_type, :stderr => @stderr)
- allow(@yc).to receive(:shell_out!).and_return(@status)
- expect(Chef::Log).to receive(:warn).exactly(2).times.with(%r{Problem parsing})
- @yc.refresh
- end
-
- it "should warn about no output from yum-dump.py" do
- @status = double("Status", :exitstatus => 0, :stdin => @stdin, :stdout => @stdout_no_output, :stderr => @stderr)
- allow(@yc).to receive(:shell_out!).and_return(@status)
- expect(Chef::Log).to receive(:warn).exactly(1).times.with(%r{no output from yum-dump.py})
- @yc.refresh
- end
-
- 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})
- end
-
- it "should parse type 'i' into an installed state for a package" do
- expect(@yc.available_version("erlang-mochiweb")).to eq(nil)
- expect(@yc.installed_version("erlang-mochiweb")).not_to eq(nil)
- end
-
- it "should parse type 'a' into an available state for a package" do
- expect(@yc.available_version("znc")).not_to eq(nil)
- expect(@yc.installed_version("znc")).to eq(nil)
- end
-
- it "should parse type 'r' into an installed and available states for a package" do
- expect(@yc.available_version("zip")).not_to eq(nil)
- expect(@yc.installed_version("zip")).not_to eq(nil)
- end
-
- it "should parse installonlypkgs from yum-dump.py options output" do
- expect(@yc.allow_multi_install).to eq(%w{kernel kernel-bigmem kernel-enterprise})
- end
- end
-
- describe "installed_version" do
- it "should take one or two arguments" do
- expect { @yc.installed_version("zip") }.not_to raise_error
- expect { @yc.installed_version("zip", "i386") }.not_to raise_error
- expect { @yc.installed_version("zip", "i386", "extra") }.to raise_error(ArgumentError)
- end
-
- it "should return version-release for matching package regardless of arch" do
- expect(@yc.installed_version("zip", "x86_64")).to eq("2.31-2.el5")
- expect(@yc.installed_version("zip", nil)).to eq("2.31-2.el5")
- end
-
- it "should return version-release for matching package and arch" do
- expect(@yc.installed_version("zip", "x86_64")).to eq("2.31-2.el5")
- expect(@yc.installed_version("zisofs-tools", "i386")).to eq(nil)
- end
-
- it "should return nil for an unmatched package" do
- expect(@yc.installed_version(nil, nil)).to eq(nil)
- expect(@yc.installed_version("test1", nil)).to eq(nil)
- expect(@yc.installed_version("test2", "x86_64")).to eq(nil)
- end
- end
-
- describe "available_version" do
- it "should take one or two arguments" do
- expect { @yc.available_version("zisofs-tools") }.not_to raise_error
- expect { @yc.available_version("zisofs-tools", "i386") }.not_to raise_error
- expect { @yc.available_version("zisofs-tools", "i386", "extra") }.to raise_error(ArgumentError)
- end
-
- it "should return version-release for matching package regardless of arch" do
- expect(@yc.available_version("zip", "x86_64")).to eq("2.31-2.el5")
- expect(@yc.available_version("zip", nil)).to eq("2.31-2.el5")
- end
-
- it "should return version-release for matching package and arch" do
- expect(@yc.available_version("zip", "x86_64")).to eq("2.31-2.el5")
- expect(@yc.available_version("zisofs-tools", "i386")).to eq(nil)
- end
-
- it "should return nil for an unmatched package" do
- expect(@yc.available_version(nil, nil)).to eq(nil)
- expect(@yc.available_version("test1", nil)).to eq(nil)
- expect(@yc.available_version("test2", "x86_64")).to eq(nil)
- end
- end
-
- describe "version_available?" do
- it "should take two or three arguments" do
- expect { @yc.version_available?("zisofs-tools") }.to raise_error(ArgumentError)
- expect { @yc.version_available?("zisofs-tools", "1.0.6-3.2.2") }.not_to raise_error
- expect { @yc.version_available?("zisofs-tools", "1.0.6-3.2.2", "x86_64") }.not_to raise_error
- end
-
- it "should return true if our package-version-arch is available" do
- expect(@yc.version_available?("zisofs-tools", "1.0.6-3.2.2", "x86_64")).to eq(true)
- end
-
- it "should return true if our package-version, no arch, is available" do
- expect(@yc.version_available?("zisofs-tools", "1.0.6-3.2.2", nil)).to eq(true)
- expect(@yc.version_available?("zisofs-tools", "1.0.6-3.2.2")).to eq(true)
- end
-
- it "should return false if our package-version-arch isn't available" do
- expect(@yc.version_available?("zisofs-tools", "1.0.6-3.2.2", "pretend")).to eq(false)
- expect(@yc.version_available?("zisofs-tools", "pretend", "x86_64")).to eq(false)
- expect(@yc.version_available?("pretend", "1.0.6-3.2.2", "x86_64")).to eq(false)
- end
-
- it "should return false if our package-version, no arch, isn't available" do
- expect(@yc.version_available?("zisofs-tools", "pretend", nil)).to eq(false)
- expect(@yc.version_available?("zisofs-tools", "pretend")).to eq(false)
- expect(@yc.version_available?("pretend", "1.0.6-3.2.2")).to eq(false)
- end
- end
-
- describe "package_repository" do
- it "should take two or three arguments" do
- expect { @yc.package_repository("zisofs-tools") }.to raise_error(ArgumentError)
- expect { @yc.package_repository("zisofs-tools", "1.0.6-3.2.2") }.not_to raise_error
- expect { @yc.package_repository("zisofs-tools", "1.0.6-3.2.2", "x86_64") }.not_to raise_error
- end
-
- it "should return repoid for package-version-arch" do
- expect(@yc.package_repository("zlib-devel", "1.2.3-3", "i386")).to eq("extras")
- expect(@yc.package_repository("zlib-devel", "1.2.3-3", "x86_64")).to eq("base")
- end
-
- it "should return repoid for package-version, no arch" do
- expect(@yc.package_repository("zisofs-tools", "1.0.6-3.2.2", nil)).to eq("extras")
- expect(@yc.package_repository("zisofs-tools", "1.0.6-3.2.2")).to eq("extras")
- end
-
- it "should return nil when no match for package-version-arch" do
- expect(@yc.package_repository("zisofs-tools", "1.0.6-3.2.2", "pretend")).to eq(nil)
- expect(@yc.package_repository("zisofs-tools", "pretend", "x86_64")).to eq(nil)
- expect(@yc.package_repository("pretend", "1.0.6-3.2.2", "x86_64")).to eq(nil)
- end
-
- it "should return nil when no match for package-version, no arch" do
- expect(@yc.package_repository("zisofs-tools", "pretend", nil)).to eq(nil)
- expect(@yc.package_repository("zisofs-tools", "pretend")).to eq(nil)
- expect(@yc.package_repository("pretend", "1.0.6-3.2.2")).to eq(nil)
- end
- end
-
- describe "reset" do
- it "should empty the installed and available packages RPMDb" do
- expect(@yc.available_version("zip", "x86_64")).to eq("2.31-2.el5")
- expect(@yc.installed_version("zip", "x86_64")).to eq("2.31-2.el5")
- @yc.reset
- expect(@yc.available_version("zip", "x86_64")).to eq(nil)
- expect(@yc.installed_version("zip", "x86_64")).to eq(nil)
- end
- end
-
- describe "package_available?" do
- it "should return true a package name is available" do
- expect(@yc.package_available?("zisofs-tools")).to eq(true)
- expect(@yc.package_available?("moo")).to eq(false)
- expect(@yc.package_available?(nil)).to eq(false)
- end
-
- it "should return true a package name + arch is available" do
- expect(@yc.package_available?("zlib-devel.i386")).to eq(true)
- expect(@yc.package_available?("zisofs-tools.x86_64")).to eq(true)
- expect(@yc.package_available?("znc-test.beta1.x86_64")).to eq(true)
- expect(@yc.package_available?("znc-test.beta1")).to eq(true)
- expect(@yc.package_available?("znc-test.test.beta1")).to eq(true)
- expect(@yc.package_available?("moo.i386")).to eq(false)
- expect(@yc.package_available?("zisofs-tools.beta")).to eq(false)
- expect(@yc.package_available?("znc-test.test")).to eq(false)
- end
- end
-
- describe "enable_extra_repo_control" do
- it "should set @extra_repo_control to arg" do
- @yc.enable_extra_repo_control("--enablerepo=test")
- expect(@yc.extra_repo_control).to eq("--enablerepo=test")
- end
-
- it "should call reload once when set to flag cache for update" do
- expect(@yc).to receive(:reload).once
- @yc.enable_extra_repo_control("--enablerepo=test")
- @yc.enable_extra_repo_control("--enablerepo=test")
- end
- end
-
- describe "disable_extra_repo_control" do
- it "should set @extra_repo_control to nil" do
- @yc.enable_extra_repo_control("--enablerepo=test")
- @yc.disable_extra_repo_control
- expect(@yc.extra_repo_control).to eq(nil)
- end
-
- it "should call reload once when cleared to flag cache for update" do
- expect(@yc).to receive(:reload).once
- @yc.enable_extra_repo_control("--enablerepo=test")
- expect(@yc).to receive(:reload).once
- @yc.disable_extra_repo_control
- @yc.disable_extra_repo_control
- end
- end
-
-end
-
-describe "Chef::Provider::Package::Yum - Multi" do
- before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @new_resource = Chef::Resource::YumPackage.new(%w{cups vim})
- @status = double("Status", :exitstatus => 0)
- @yum_cache = double(
- "Chef::Provider::Yum::YumCache",
- :reload_installed => true,
- :reset => true,
- :installed_version => "XXXX",
- :candidate_version => "YYYY",
- :package_available? => true,
- :version_available? => true,
- :allow_multi_install => [ "kernel" ],
- :package_repository => "base",
- :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")
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- @pid = double("PID")
- end
-
- describe "when evaluating the correctness of the resource" do
- it "raises an error if the array lengths of package name, arch, and version do not match up" do
- @new_resource.version(["1.1"])
- @new_resource.arch(%w{x86_64 i386 i686})
- expect { @provider.check_resource_semantics! }.to raise_error(Chef::Exceptions::InvalidResourceSpecification)
- end
- end
-
- describe "when loading the current system state" do
- it "should create a current resource with the name of the new_resource" do
- @provider.load_current_resource
- expect(@provider.current_resource.name).to eq("cups, vim")
- end
-
- it "should set the current resources package name to the new resources package name" do
- @provider.load_current_resource
- expect(@provider.current_resource.package_name).to eq(%w{cups vim})
- end
-
- it "should set the installed version to nil on the current resource if no installed package" do
- allow(@yum_cache).to receive(:installed_version).and_return(nil)
- @provider.load_current_resource
- expect(@provider.current_resource.version).to eq([nil, nil])
- end
-
- it "should set the installed version if yum has one" do
- allow(@yum_cache).to receive(:installed_version).with("cups", nil).and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("vim", nil).and_return("1.0")
- allow(@yum_cache).to receive(:candidate_version).with("cups", nil).and_return("1.2.4-11.18.el5_2.3")
- allow(@yum_cache).to receive(:candidate_version).with("vim", nil).and_return("1.5")
- @provider.load_current_resource
- expect(@provider.current_resource.version).to eq(["1.2.4-11.18.el5", "1.0"])
- end
-
- it "should set the candidate version if yum info has one" do
- allow(@yum_cache).to receive(:installed_version).with("cups", nil).and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("vim", nil).and_return("1.0")
- allow(@yum_cache).to receive(:candidate_version).with("cups", nil).and_return("1.2.4-11.18.el5_2.3")
- allow(@yum_cache).to receive(:candidate_version).with("vim", nil).and_return("1.5")
- @provider.load_current_resource
- expect(@provider.candidate_version).to eql(["1.2.4-11.18.el5_2.3", "1.5"])
- end
-
- it "should return the current resouce" do
- expect(@provider.load_current_resource).to eql(@provider.current_resource)
- end
-
- describe "when version constraint in package_name" do
- it "should set package_version if no existing package_name is found and new_package_name is available" do
- @new_resource = Chef::Resource::YumPackage.new(["cups = 1.2.4-11.18.el5_2.3", "emacs = 24.4"])
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- allow(@yum_cache).to receive(:package_available?) { |pkg| %w{cups emacs}.include?(pkg) ? true : false }
- allow(@yum_cache).to receive(:candidate_version) do |pkg|
- if pkg == "cups"
- "1.2.4-11.18.el5_2.3"
- elsif pkg == "emacs"
- "24.4"
- end
- end
- allow(@yum_cache).to receive(:packages_from_require) do |pkg|
- if pkg.name == "cups"
- [Chef::Provider::Package::Yum::RPMDbPackage.new("cups", "1.2.4-11.18.el5_2.3", "noarch", [], false, true, "base")]
- elsif pkg.name == "emacs"
- [Chef::Provider::Package::Yum::RPMDbPackage.new("emacs", "24.4", "noarch", [], false, true, "base")]
- end
- end
- expect(Chef::Log).to receive(:debug).exactly(2).times.with(%r{matched 1 package,})
- expect(Chef::Log).to receive(:debug).exactly(1).times.with(%r{candidate version: 1.2.4-11.18.el5_2.3})
- expect(Chef::Log).to receive(:debug).exactly(1).times.with(%r{candidate version: 24.4})
- expect(Chef::Log).to receive(:debug).at_least(2).times.with(%r{checking yum info})
- @provider.load_current_resource
- expect(@provider.new_resource.package_name).to eq(%w{cups emacs})
- expect(@provider.new_resource.version).to eq(["1.2.4-11.18.el5_2.3", "24.4"])
- expect(@provider.send(:package_name_array)).to eq(%w{cups emacs})
- expect(@provider.send(:new_version_array)).to eq(["1.2.4-11.18.el5_2.3", "24.4"])
- end
- end
- end
-
- describe "when installing a package" do
- it "should run yum install with the package name and version" do
- @provider.load_current_resource
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- allow(@yum_cache).to receive(:installed_version).with("cups", nil).and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("vim", nil).and_return("0.9")
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5 vim-1.0"
- )
- @provider.install_package(%w{cups vim}, ["1.2.4-11.19.el5", "1.0"])
- end
-
- it "should not run yum install with nil package name" do
- @provider.load_current_resource
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5"
- )
- @provider.install_package(["cups", nil], ["1.2.4-11.19.el5", nil])
- end
-
- it "should run yum install with the package name, version and arch" do
- @provider.load_current_resource
- @new_resource.arch(%w{i386 i386})
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5.i386 vim-1.0.i386"
- )
- @provider.install_package(%w{cups vim}, ["1.2.4-11.19.el5", "1.0"])
- end
-
- it "installs the package with the options given in the resource" do
- @provider.load_current_resource
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
- allow(@yum_cache).to receive(:installed_version).with("cups", nil).and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("vim", nil).and_return("0.9")
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y --disablerepo epmd install cups-1.2.4-11.19.el5 vim-1.0"
- )
- @new_resource.options("--disablerepo epmd")
- @provider.install_package(%w{cups vim}, ["1.2.4-11.19.el5", "1.0"])
- end
-
- it "should run yum install with the package name and version when name has arch" do
- @new_resource = Chef::Resource::YumPackage.new(["cups.x86_64", "vim"])
- @provider = Chef::Provider::Package::Yum.new(@new_resource, @run_context)
- allow(Chef::Provider::Package::Yum::RPMUtils).to receive(:rpmvercmp).and_return(-1)
-
- # Inside of load_current_resource() we'll call parse_arch for cups,
- # and we need to craft the right response. The default mock setup above
- # will just return valid versions all the time which won't work for this
- # test.
- allow(@yum_cache).to receive(:installed_version).with("cups", "x86_64").and_return("XXXX")
- allow(@yum_cache).to receive(:candidate_version).with("cups", "x86_64").and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("cups.x86_64").and_return(nil)
- allow(@yum_cache).to receive(:candidate_version).with("cups.x86_64").and_return(nil)
-
- # Normal mock's for the idempotency check
- allow(@yum_cache).to receive(:installed_version).with("cups", nil).and_return("1.2.4-11.18.el5")
- allow(@yum_cache).to receive(:installed_version).with("vim", nil).and_return("0.9")
-
- @provider.load_current_resource
- expect(@provider).to receive(:yum_command).with(
- "-d0 -e0 -y install cups-1.2.4-11.19.el5.x86_64 vim-1.0"
- )
- @provider.install_package(%w{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 b20a548c73..6795f9e051 100644
--- a/spec/unit/provider/package/zypper_spec.rb
+++ b/spec/unit/provider/package/zypper_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,22 +30,22 @@ describe Chef::Provider::Package::Zypper do
Chef::Provider::Package::Zypper.new(new_resource, run_context)
end
- let(:status) { double(:stdout => "\n", :exitstatus => 0) }
+ let(:status) { double(stdout: "\n", exitstatus: 0) }
before(:each) do
allow(Chef::Resource::Package).to receive(:new).and_return(current_resource)
- allow(provider).to receive(:shell_out!).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
allow(provider).to receive(:`).and_return("2.0")
end
def shell_out_expectation(*command, **options)
options[:timeout] ||= 900
- expect(provider).to receive(:shell_out).with(*command, **options)
+ expect(provider).to receive(:shell_out_compacted).with(*command, **options)
end
def shell_out_expectation!(*command, **options)
options[:timeout] ||= 900
- expect(provider).to receive(:shell_out!).with(*command, **options)
+ expect(provider).to receive(:shell_out_compacted!).with(*command, **options)
end
describe "when loading the current package state" do
@@ -67,39 +67,47 @@ describe Chef::Provider::Package::Zypper do
end
it "should set the installed version to nil on the current resource if zypper info installed version is (none)" do
- allow(provider).to receive(:shell_out).and_return(status)
+ allow(provider).to receive(:shell_out_compacted).and_return(status)
expect(current_resource).to receive(:version).with([nil]).and_return(true)
provider.load_current_resource
end
it "should set the installed version if zypper info has one (zypper version < 1.13.0)" do
- status = double(:stdout => "Version: 1.0\nInstalled: Yes\n", :exitstatus => 0)
+ status = double(stdout: "Version: 1.0\nInstalled: Yes\n", exitstatus: 0)
- allow(provider).to receive(:shell_out!).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
expect(current_resource).to receive(:version).with(["1.0"]).and_return(true)
provider.load_current_resource
end
it "should set the installed version if zypper info has one (zypper version >= 1.13.0)" do
- status = double(:stdout => "Version : 1.0 \nInstalled : Yes \n", :exitstatus => 0)
+ status = double(stdout: "Version : 1.0 \nInstalled : Yes \n", exitstatus: 0)
- allow(provider).to receive(:shell_out!).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
+ expect(current_resource).to receive(:version).with(["1.0"]).and_return(true)
+ provider.load_current_resource
+ end
+
+ it "should set the installed version if zypper info has one (zypper version >= 1.13.17)" do
+ status = double(stdout: "Version : 1.0\nInstalled : Yes (automatically)\n", exitstatus: 0)
+
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
expect(current_resource).to receive(:version).with(["1.0"]).and_return(true)
provider.load_current_resource
end
it "should set the candidate version if zypper info has one (zypper version < 1.13.0)" do
- status = double(:stdout => "Version: 1.0\nInstalled: No\nStatus: out-of-date (version 0.9 installed)", :exitstatus => 0)
+ status = double(stdout: "Version: 1.0\nInstalled: No\nStatus: out-of-date (version 0.9 installed)", exitstatus: 0)
- allow(provider).to receive(:shell_out!).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
provider.load_current_resource
expect(provider.candidate_version).to eql(["1.0"])
end
it "should set the candidate version if zypper info has one (zypper version >= 1.13.0)" do
- status = double(:stdout => "Version : 1.0 \nInstalled : No \nStatus : out-of-date (version 0.9 installed)", :exitstatus => 0)
+ status = double(stdout: "Version : 1.0 \nInstalled : No \nStatus : out-of-date (version 0.9 installed)", exitstatus: 0)
- allow(provider).to receive(:shell_out!).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).and_return(status)
provider.load_current_resource
expect(provider.candidate_version).to eql(["1.0"])
end
@@ -140,6 +148,14 @@ describe Chef::Provider::Package::Zypper do
provider.install_package(["emacs"], ["1.0"])
end
+ it "setting the property should allow downgrade" do
+ new_resource.allow_downgrade true
+ shell_out_expectation!(
+ "zypper", "--non-interactive", "install", "--auto-agree-with-licenses", "--oldpackage", "emacs=1.0"
+ )
+ provider.install_package(["emacs"], ["1.0"])
+ end
+
it "should add user provided options to the command" do
new_resource.options "--user-provided"
shell_out_expectation!(
@@ -251,6 +267,38 @@ describe Chef::Provider::Package::Zypper do
end
end
+ describe "action_lock" do
+ it "should lock if the package is not already locked" do
+ expect(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "--non-interactive", "info", new_resource.package_name, timeout: 900
+ ).and_return(status)
+ expect(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "locks", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "1 | somethingelse | package | (any)"
+ ))
+ expect(provider).to receive(:lock_package).with(["cups"], [nil])
+
+ provider.load_current_resource
+ provider.action_lock
+ end
+
+ it "should not lock if the package is already locked" do
+ expect(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "--non-interactive", "info", new_resource.package_name, timeout: 900
+ ).and_return(status)
+ expect(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "locks", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "1 | cups | package | (any)"
+ ))
+ expect(provider).to_not receive(:lock_package)
+
+ provider.load_current_resource
+ provider.action_lock
+ end
+ end
+
describe "lock_package" do
it "should run zypper addlock with the package name" do
shell_out_expectation!(
@@ -274,6 +322,37 @@ describe Chef::Provider::Package::Zypper do
end
end
+ describe "action_unlock" do
+ it "should unlock if the package is not already unlocked" do
+ allow(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "--non-interactive", "info", new_resource.package_name, timeout: 900
+ ).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "locks", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "1 | cups | package | (any)"
+ ))
+ expect(provider).to receive(:unlock_package).with(["cups"], [nil])
+
+ provider.load_current_resource
+ provider.action_unlock
+ end
+ it "should not unlock if the package is already unlocked" do
+ allow(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "--non-interactive", "info", new_resource.package_name, timeout: 900
+ ).and_return(status)
+ allow(provider).to receive(:shell_out_compacted!).with(
+ "zypper", "locks", timeout: 900
+ ).and_return(instance_double(
+ Mixlib::ShellOut, stdout: "1 | somethingelse | package | (any)"
+ ))
+ expect(provider).to_not receive(:unlock_package)
+
+ provider.load_current_resource
+ provider.action_unlock
+ end
+ end
+
describe "unlock_package" do
it "should run zypper removelock with the package name" do
shell_out_expectation!(
diff --git a/spec/unit/provider/package_spec.rb b/spec/unit/provider/package_spec.rb
index 122e58efb7..904e339e47 100644
--- a/spec/unit/provider/package_spec.rb
+++ b/spec/unit/provider/package_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software, Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -26,17 +26,24 @@ describe Chef::Provider::Package do
node
end
let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
- let(:new_resource) { Chef::Resource::Package.new("emacs") }
- let(:current_resource) { Chef::Resource::Package.new("emacs") }
+ let(:new_resource) { Chef::Resource::Package.new("install emacs") }
+ let(:current_resource) { Chef::Resource::Package.new("install emacs") }
let(:candidate_version) { "1.0" }
let(:provider) do
+ new_resource.package_name = "emacs"
+ current_resource.package_name = "emacs"
provider = Chef::Provider::Package.new(new_resource, run_context)
provider.current_resource = current_resource
provider.candidate_version = candidate_version
provider
end
+ before do
+ allow(run_context).to receive(:logger).and_return(logger)
+ end
+
describe "when installing a package" do
before(:each) do
provider.current_resource = current_resource
@@ -57,7 +64,7 @@ describe Chef::Provider::Package do
it "should call preseed_package if a response_file is given" do
new_resource.response_file("foo")
expect(provider).to receive(:get_preseed_file).with(
- new_resource.name,
+ new_resource.package_name,
provider.candidate_version
).and_return("/var/cache/preseed-test")
@@ -74,7 +81,7 @@ describe Chef::Provider::Package do
it "should install the package at the candidate_version if it is not already installed" do
expect(provider).to receive(:install_package).with(
- new_resource.name,
+ new_resource.package_name,
provider.candidate_version
).and_return(true)
provider.run_action(:install)
@@ -84,7 +91,7 @@ describe Chef::Provider::Package do
it "should install the package at the version specified if it is not already installed" do
new_resource.version("1.0")
expect(provider).to receive(:install_package).with(
- new_resource.name,
+ new_resource.package_name,
new_resource.version
).and_return(true)
provider.run_action(:install)
@@ -95,7 +102,7 @@ describe Chef::Provider::Package do
new_resource.version("1.0")
allow(current_resource).to receive(:version).and_return("0.99")
expect(provider).to receive(:install_package).with(
- new_resource.name,
+ new_resource.package_name,
new_resource.version
).and_return(true)
provider.run_action(:install)
@@ -143,7 +150,7 @@ describe Chef::Provider::Package do
it "should upgrade the package if the current version is not the candidate version" do
expect(provider).to receive(:upgrade_package).with(
- new_resource.name,
+ new_resource.package_name,
provider.candidate_version
).and_return(true)
provider.run_action(:upgrade)
@@ -164,7 +171,7 @@ describe Chef::Provider::Package do
it "should print the word 'uninstalled' if there was no original version" do
allow(current_resource).to receive(:version).and_return(nil)
- expect(Chef::Log).to receive(:info).with("package[emacs] upgraded emacs to 1.0")
+ expect(logger).to receive(:info).with("package[install emacs] upgraded emacs to 1.0")
provider.run_action(:upgrade)
expect(new_resource).to be_updated_by_last_action
end
@@ -285,7 +292,7 @@ describe Chef::Provider::Package do
expect(provider).to receive(:get_preseed_file).and_return("/var/cache/preseed-test")
allow(provider).to receive(:preseed_package).and_return(true)
allow(provider).to receive(:reconfig_package).and_return(true)
- expect(Chef::Log).to receive(:info).with("package[emacs] reconfigured")
+ expect(logger).to receive(:info).with("package[install emacs] reconfigured")
expect(provider).to receive(:reconfig_package)
provider.run_action(:reconfig)
expect(new_resource).to be_updated
@@ -294,7 +301,7 @@ describe Chef::Provider::Package do
it "should debug log and not reconfigure the package if the package is not installed" do
allow(current_resource).to receive(:version).and_return(nil)
- expect(Chef::Log).to receive(:debug).with("package[emacs] is NOT installed - nothing to do")
+ expect(logger).to receive(:trace).with("package[install emacs] is NOT installed - nothing to do")
expect(provider).not_to receive(:reconfig_package)
provider.run_action(:reconfig)
expect(new_resource).not_to be_updated_by_last_action
@@ -303,7 +310,7 @@ describe Chef::Provider::Package do
it "should debug log and not reconfigure the package if no response_file is given" do
allow(current_resource).to receive(:version).and_return("1.0")
allow(new_resource).to receive(:response_file).and_return(nil)
- expect(Chef::Log).to receive(:debug).with("package[emacs] no response_file provided - nothing to do")
+ expect(logger).to receive(:trace).with("package[install emacs] no response_file provided - nothing to do")
expect(provider).not_to receive(:reconfig_package)
provider.run_action(:reconfig)
expect(new_resource).not_to be_updated_by_last_action
@@ -314,7 +321,7 @@ describe Chef::Provider::Package do
allow(new_resource).to receive(:response_file).and_return(true)
expect(provider).to receive(:get_preseed_file).and_return(false)
allow(provider).to receive(:preseed_package).and_return(false)
- expect(Chef::Log).to receive(:debug).with("package[emacs] preseeding has not changed - nothing to do")
+ expect(logger).to receive(:trace).with("package[install emacs] preseeding has not changed - nothing to do")
expect(provider).not_to receive(:reconfig_package)
provider.run_action(:reconfig)
expect(new_resource).not_to be_updated_by_last_action
@@ -323,24 +330,35 @@ describe Chef::Provider::Package do
describe "When locking the package" do
before(:each) do
- allow(provider).to receive(:lock_package).and_return(true)
+ allow(provider).to receive(:lock_package).with(
+ new_resource.package_name,
+ nil
+ ).and_return(true)
end
it "should lock the package if it is unlocked" do
- allow(provider).to receive(:package_locked).and_return(false)
- expect(provider).to receive(:lock_package)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(false)
provider.run_action(:lock)
end
it "should not lock the package if it is already locked" do
- allow(provider).to receive(:package_locked).and_return(true)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(true)
expect(provider).not_to receive(:lock_package)
provider.run_action(:lock)
expect(new_resource).not_to be_updated_by_last_action
end
it "should set the resource to updated if it locks the package" do
- allow(provider).to receive(:package_locked).and_return(false)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(false)
provider.run_action(:lock)
expect(new_resource).to be_updated
end
@@ -352,20 +370,29 @@ describe Chef::Provider::Package do
end
it "should unlock the package if it is locked" do
- allow(provider).to receive(:package_locked).and_return(true)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(true)
expect(provider).to receive(:unlock_package)
provider.run_action(:unlock)
end
it "should not unlock the package if it is already unlocked" do
- allow(provider).to receive(:package_locked).and_return(false)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(false)
expect(provider).not_to receive(:unlock_package)
provider.run_action(:unlock)
expect(new_resource).not_to be_updated_by_last_action
end
it "should set the resource to updated if it unlocks the package" do
- allow(provider).to receive(:package_locked).and_return(true)
+ allow(provider).to receive(:package_locked).with(
+ new_resource.package_name,
+ nil
+ ).and_return(true)
provider.run_action(:unlock)
expect(new_resource).to be_updated
end
@@ -915,7 +942,7 @@ describe "Chef::Provider::Package - Multi" do
end
[ :shell_out_with_timeout, :shell_out_with_timeout! ].each do |method|
- stubbed_method = method == :shell_out_with_timeout! ? :shell_out! : :shell_out
+ stubbed_method = method == :shell_out_with_timeout! ? :shell_out_compacted! : :shell_out_compacted
[ %w{command arg1 arg2}, "command arg1 arg2" ].each do |command|
it "#{method} defaults to 900 seconds" do
expect(provider).to receive(stubbed_method).with(*command, timeout: 900)
diff --git a/spec/unit/provider/powershell_script_spec.rb b/spec/unit/provider/powershell_script_spec.rb
index d7a1620530..79d84e61dc 100644
--- a/spec/unit/provider/powershell_script_spec.rb
+++ b/spec/unit/provider/powershell_script_spec.rb
@@ -25,7 +25,7 @@ describe Chef::Provider::PowershellScript, "action_run" do
node.default["kernel"] = Hash.new
node.default["kernel"][:machine] = :x86_64.to_s
if ! powershell_version.nil?
- node.default[:languages] = { :powershell => { :version => powershell_version } }
+ node.default[:languages] = { powershell: { version: powershell_version } }
end
node
end
@@ -84,7 +84,7 @@ describe Chef::Provider::PowershellScript, "action_run" do
provider_flags.find do |value|
execution_policy_index += 1
- execution_policy_specified = value.casecmp("-ExecutionPolicy".downcase).zero?
+ execution_policy_specified = value.casecmp("-ExecutionPolicy".downcase) == 0
end
execution_policy = execution_policy_specified ? provider_flags[execution_policy_index] : nil
diff --git a/spec/unit/provider/registry_key_spec.rb b/spec/unit/provider/registry_key_spec.rb
index 3fb9468f5d..3563af4dc4 100644
--- a/spec/unit/provider/registry_key_spec.rb
+++ b/spec/unit/provider/registry_key_spec.rb
@@ -275,20 +275,20 @@ describe Chef::Provider::RegistryKey do
context "when the key data is safe" do
let(:keyname) { 'HKLM\Software\Opscode\Testing\Safe' }
- let(:testval1) { { :name => "one", :type => :string, :data => "1" } }
- let(:testval1_wrong_type) { { :name => "one", :type => :multi_string, :data => "1" } }
- let(:testval1_wrong_data) { { :name => "one", :type => :string, :data => "2" } }
- let(:testval2) { { :name => "two", :type => :string, :data => "2" } }
+ let(:testval1) { { name: "one", type: :string, data: "1" } }
+ let(:testval1_wrong_type) { { name: "one", type: :multi_string, data: "1" } }
+ let(:testval1_wrong_data) { { name: "one", type: :string, data: "2" } }
+ let(:testval2) { { name: "two", type: :string, data: "2" } }
it_should_behave_like "a registry key"
end
context "when the key data is unsafe" do
let(:keyname) { 'HKLM\Software\Opscode\Testing\Unsafe' }
- let(:testval1) { { :name => "one", :type => :binary, :data => 255.chr * 1 } }
- let(:testval1_wrong_type) { { :name => "one", :type => :string, :data => 255.chr * 1 } }
- let(:testval1_wrong_data) { { :name => "one", :type => :binary, :data => 254.chr * 1 } }
- let(:testval2) { { :name => "two", :type => :binary, :data => 0.chr * 1 } }
+ let(:testval1) { { name: "one", type: :binary, data: 255.chr * 1 } }
+ let(:testval1_wrong_type) { { name: "one", type: :string, data: 255.chr * 1 } }
+ let(:testval1_wrong_data) { { name: "one", type: :binary, data: 254.chr * 1 } }
+ let(:testval2) { { name: "two", type: :binary, data: 0.chr * 1 } }
it_should_behave_like "a registry key"
end
@@ -296,8 +296,8 @@ describe Chef::Provider::RegistryKey do
describe "action_create" do
context "when key exists and type matches" do
let(:keyname) { 'hklm\\software\\opscode\\testing\\dword' }
- let(:dword_passed_as_integer) { { :name => "one", :type => :dword, :data => 12345 } }
- let(:testval1) { { :name => "one", :type => :dword, :data => "12345" } }
+ let(:dword_passed_as_integer) { { name: "one", type: :dword, data: 12345 } }
+ let(:testval1) { { name: "one", type: :dword, data: "12345" } }
before do
expect(@double_registry).to receive(:key_exists?).twice.with(keyname).and_return(true)
end
@@ -313,35 +313,41 @@ describe Chef::Provider::RegistryKey do
end
describe Chef::Provider::RegistryKey, "key_missing?" do
- let(:provider) { Chef::Provider::RegistryKey.new(nil, nil) }
+ let(:node) { Chef::Node.new }
+ let(:events) { double("Chef::Events").as_null_object }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
+ let(:new_resource) { Chef::Resource::RegistryKey.new("emacs") }
+ let(:provider) { Chef::Provider::RegistryKey.new(new_resource, run_context) }
+
let(:all_keys_present_in_all_hash) do
- [ { :name => "input1_value1", :type => :string, :data => "my_value1" },
- { :name => "input1_value2", :type => :string, :data => "my_value2" },
+ [ { name: "input1_value1", type: :string, data: "my_value1" },
+ { name: "input1_value2", type: :string, data: "my_value2" },
]
end
let(:type_key_not_present_in_any_hash) do
- [ { :name => "input2_value1", :data => "my_value1" },
- { :name => "input2_value2", :data => "my_value2" },
+ [ { name: "input2_value1", data: "my_value1" },
+ { name: "input2_value2", data: "my_value2" },
]
end
let(:type_key_not_present_in_some_hash) do
- [ { :name => "input3_value1", :data => "my_value1" },
- { :name => "input3_value2", :type => :string, :data => "my_value2" },
+ [ { name: "input3_value1", data: "my_value1" },
+ { name: "input3_value2", type: :string, data: "my_value2" },
]
end
let(:data_key_not_present_in_any_hash) do
- [ { :name => "input4_value1", :type => :string },
- { :name => "input4_value2", :type => :string },
+ [ { name: "input4_value1", type: :string },
+ { name: "input4_value2", type: :string },
]
end
let(:data_key_not_present_in_some_hash) do
- [ { :name => "input5_value1", :type => :string, :data => "my_value1" },
- { :name => "input5_value2", :type => :string },
+ [ { name: "input5_value1", type: :string, data: "my_value1" },
+ { name: "input5_value2", type: :string },
]
end
let(:only_name_key_present_in_all_hash) do
- [ { :name => "input6_value1" },
- { :name => "input6_value2" },
+ [ { name: "input6_value1" },
+ { name: "input6_value2" },
]
end
diff --git a/spec/unit/provider/remote_directory_spec.rb b/spec/unit/provider/remote_directory_spec.rb
index cb1b6e3cd8..d391da3010 100644
--- a/spec/unit/provider/remote_directory_spec.rb
+++ b/spec/unit/provider/remote_directory_spec.rb
@@ -193,7 +193,7 @@ describe Chef::Provider::RemoteDirectory do
expect(::File.exist?(@destination_dir + "/a/multiply/nested/directory/qux.txt")).to be_falsey
end
- it "removes directory symlinks properly", :not_supported_on_win2k3 do
+ it "removes directory symlinks properly" do
symlinked_dir_path = @destination_dir + "/symlinked_dir"
@provider.action = :create
@provider.run_action
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 a80aa38e77..5e661ba3d7 100644
--- a/spec/unit/provider/remote_file/cache_control_data_spec.rb
+++ b/spec/unit/provider/remote_file/cache_control_data_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2013-2016, Chef Software Inc.
+# Copyright:: Copyright 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -45,8 +45,8 @@ describe Chef::Provider::RemoteFile::CacheControlData do
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)
+ expect(Chef::FileCache).to receive(:key?).with(cache_path).and_return(false)
+ expect(Chef::FileCache).to receive(:key?).with(old_cache_path).and_return(false)
end
context "and there is no current copy of the file" do
@@ -93,7 +93,7 @@ describe Chef::Provider::RemoteFile::CacheControlData do
context "when the cache control data uses sha256 for its name" do
before do
- expect(Chef::FileCache).to receive(:has_key?).with(cache_path).and_return(true)
+ expect(Chef::FileCache).to receive(:key?).with(cache_path).and_return(true)
expect(Chef::FileCache).to receive(:load).with(cache_path).and_return(cache_json_data)
end
@@ -118,7 +118,7 @@ describe Chef::Provider::RemoteFile::CacheControlData do
context "and the cached checksum matches the on-disk copy" do
context "when the filename uses sha256" do
before do
- expect(Chef::FileCache).not_to receive(:has_key?).with(old_cache_path)
+ expect(Chef::FileCache).not_to receive(:key?).with(old_cache_path)
end
it "populates the cache control data" do
expect(cache_control_data.etag).to eq(etag)
@@ -148,8 +148,8 @@ describe Chef::Provider::RemoteFile::CacheControlData do
context "when the filename uses md5" 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(true)
+ expect(Chef::FileCache).to receive(:key?).with(cache_path).and_return(false)
+ expect(Chef::FileCache).to receive(:key?).with(old_cache_path).and_return(true)
expect(Chef::FileCache).to receive(:load).with(old_cache_path).and_return(cache_json_data)
end
diff --git a/spec/unit/provider/remote_file/content_spec.rb b/spec/unit/provider/remote_file/content_spec.rb
index 307eb98187..1afc95fa48 100644
--- a/spec/unit/provider/remote_file/content_spec.rb
+++ b/spec/unit/provider/remote_file/content_spec.rb
@@ -84,7 +84,7 @@ describe Chef::Provider::RemoteFile::Content do
describe "when the fetcher returns nil for the tempfile" do
before do
- http_fetcher = double("Chef::Provider::RemoteFile::HTTP", :fetch => nil)
+ http_fetcher = double("Chef::Provider::RemoteFile::HTTP", fetch: nil)
expect(Chef::Provider::RemoteFile::Fetcher).to receive(:for_resource).with(@uri, new_resource, current_resource).and_return(http_fetcher)
end
@@ -97,7 +97,7 @@ describe Chef::Provider::RemoteFile::Content do
let(:mtime) { Time.now }
let(:tempfile) { double("Tempfile") }
- let(:http_fetcher) { double("Chef::Provider::RemoteFile::HTTP", :fetch => tempfile) }
+ let(:http_fetcher) { double("Chef::Provider::RemoteFile::HTTP", fetch: tempfile) }
before do
expect(Chef::Provider::RemoteFile::Fetcher).to receive(:for_resource).with(@uri, new_resource, current_resource).and_return(http_fetcher)
@@ -199,7 +199,7 @@ describe Chef::Provider::RemoteFile::Content do
before do
@tempfile = double("Tempfile")
mtime = Time.now
- http_fetcher_works = double("Chef::Provider::RemoteFile::HTTP", :fetch => @tempfile)
+ http_fetcher_works = double("Chef::Provider::RemoteFile::HTTP", fetch: @tempfile)
expect(Chef::Provider::RemoteFile::Fetcher).to receive(:for_resource).with(@uri1, new_resource, current_resource).and_return(http_fetcher_works)
end
@@ -236,7 +236,7 @@ describe Chef::Provider::RemoteFile::Content do
expect(URI).not_to receive(:parse).with(new_resource.source[1])
@tempfile = double("Tempfile")
mtime = Time.now
- http_fetcher_works = double("Chef::Provider::RemoteFile::HTTP", :fetch => @tempfile)
+ http_fetcher_works = double("Chef::Provider::RemoteFile::HTTP", fetch: @tempfile)
expect(Chef::Provider::RemoteFile::Fetcher).to receive(:for_resource).with(@uri0, new_resource, current_resource).and_return(http_fetcher_works)
end
diff --git a/spec/unit/provider/remote_file/fetcher_spec.rb b/spec/unit/provider/remote_file/fetcher_spec.rb
index f5b32800f2..b110e2c03a 100644
--- a/spec/unit/provider/remote_file/fetcher_spec.rb
+++ b/spec/unit/provider/remote_file/fetcher_spec.rb
@@ -46,7 +46,7 @@ describe Chef::Provider::RemoteFile::Fetcher do
end
describe "when passed an http url" do
- let(:uri) { double("uri", :scheme => "http" ) }
+ let(:uri) { double("uri", scheme: "http" ) }
before do
expect(Chef::Provider::RemoteFile::HTTP).to receive(:new).and_return(fetcher_instance)
end
@@ -56,7 +56,7 @@ describe Chef::Provider::RemoteFile::Fetcher do
end
describe "when passed an https url" do
- let(:uri) { double("uri", :scheme => "https" ) }
+ let(:uri) { double("uri", scheme: "https" ) }
before do
expect(Chef::Provider::RemoteFile::HTTP).to receive(:new).and_return(fetcher_instance)
end
@@ -66,7 +66,7 @@ describe Chef::Provider::RemoteFile::Fetcher do
end
describe "when passed an ftp url" do
- let(:uri) { double("uri", :scheme => "ftp" ) }
+ let(:uri) { double("uri", scheme: "ftp" ) }
before do
expect(Chef::Provider::RemoteFile::FTP).to receive(:new).and_return(fetcher_instance)
end
@@ -76,7 +76,7 @@ describe Chef::Provider::RemoteFile::Fetcher do
end
describe "when passed a file url" do
- let(:uri) { double("uri", :scheme => "file" ) }
+ let(:uri) { double("uri", scheme: "file" ) }
before do
expect(Chef::Provider::RemoteFile::LocalFile).to receive(:new).and_return(fetcher_instance)
end
@@ -86,7 +86,7 @@ describe Chef::Provider::RemoteFile::Fetcher do
end
describe "when passed a url we do not recognize" do
- let(:uri) { double("uri", :scheme => "xyzzy" ) }
+ let(:uri) { double("uri", scheme: "xyzzy" ) }
it "throws an ArgumentError exception" do
expect { described_class.for_resource(uri, new_resource, current_resource) }.to raise_error(ArgumentError)
end
diff --git a/spec/unit/provider/remote_file/ftp_spec.rb b/spec/unit/provider/remote_file/ftp_spec.rb
index b2fbb7300c..72bb910e66 100644
--- a/spec/unit/provider/remote_file/ftp_spec.rb
+++ b/spec/unit/provider/remote_file/ftp_spec.rb
@@ -108,7 +108,7 @@ describe Chef::Provider::RemoteFile::FTP do
before do
current_resource.checksum(current_resource_checksum)
- #Chef::Provider::RemoteFile::CacheControlData.should_receive(:load_and_validate).with(uri, current_resource_checksum).and_return(cache_control_data)
+ # Chef::Provider::RemoteFile::CacheControlData.should_receive(:load_and_validate).with(uri, current_resource_checksum).and_return(cache_control_data)
end
it "should connect to the host from the uri on the default port 21" do
diff --git a/spec/unit/provider/remote_file/http_spec.rb b/spec/unit/provider/remote_file/http_spec.rb
index f58a3d3c14..8ece1a854b 100644
--- a/spec/unit/provider/remote_file/http_spec.rb
+++ b/spec/unit/provider/remote_file/http_spec.rb
@@ -157,9 +157,9 @@ describe Chef::Provider::RemoteFile::HTTP do
let(:expected_http_opts) { {} }
let(:expected_http_args) { [uri, expected_http_opts] }
- let(:tempfile_path) { "/tmp/chef-mock-tempfile-abc123" }
+ let(:tempfile_path) { tempfile.path }
- let(:tempfile) { double(Tempfile, :path => tempfile_path, :close => nil) }
+ let(:tempfile) { Tempfile.open("muhtempfile") }
let(:last_response) { {} }
@@ -171,7 +171,7 @@ describe Chef::Provider::RemoteFile::HTTP do
let(:rest) do
rest = double(Chef::HTTP::Simple)
- allow(rest).to receive(:streaming_request).and_return(tempfile)
+ allow_any_instance_of(Chef::FileContentManagement::Tempfile).to receive(:tempfile).and_return(tempfile)
allow(rest).to receive(:last_response).and_return(last_response)
rest
end
@@ -185,21 +185,37 @@ 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 clean up the tempfile, and return a nil when streaming_request returns nil" do
+ # Streaming request returns nil for a 304 not modified (etags / last-modified)
+ expect(rest).to receive(:streaming_request).with(uri, {}, tempfile).and_return(nil)
+ expect(tempfile).to receive(:close)
+ expect(tempfile).to receive(:unlink)
+ expect(fetcher.fetch).to be_nil
+ end
+
+ context "with progress reports" do
+ let(:fetched_content_checksum) { "e2a8938cc31754f6c067b35aab1d0d4864272e9bf8504536ef3e79ebf8432305" }
- 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
+ before do
+ expect(cache_control_data).to receive(:save)
+ expect(Chef::Digester).to receive(:checksum_for_file).with(tempfile_path).and_return(fetched_content_checksum)
+ Chef::Config[:show_download_progress] = true
end
+ it "should yield its progress" do
+ expect(rest).to receive(:streaming_request_with_progress).with(uri, {}, tempfile).and_yield(50, 100).and_yield(70, 100).and_return(tempfile)
+ expect(event_dispatcher).to receive(:formatter?).and_return(true)
+ expect(event_dispatcher).to receive(:resource_update_progress).with(new_resource, 50, 100, 10).ordered
+ expect(event_dispatcher).to receive(:resource_update_progress).with(new_resource, 70, 100, 10).ordered
+ fetcher.fetch
+ end
end
describe "and the request returns new content" do
-
let(:fetched_content_checksum) { "e2a8938cc31754f6c067b35aab1d0d4864272e9bf8504536ef3e79ebf8432305" }
before do
+ expect(rest).to receive(:streaming_request).with(uri, {}, tempfile).and_return(tempfile)
expect(cache_control_data).to receive(:save)
expect(Chef::Digester).to receive(:checksum_for_file).with(tempfile_path).and_return(fetched_content_checksum)
end
@@ -212,20 +228,6 @@ describe Chef::Provider::RemoteFile::HTTP do
expect(cache_control_data.checksum).to eq(fetched_content_checksum)
end
- context "with progress reports" do
- before do
- Chef::Config[:show_download_progress] = true
- end
-
- it "should yield its progress" do
- allow(rest).to receive(:streaming_request_with_progress).and_yield(50, 100).and_yield(70, 100).and_return(tempfile)
- expect(event_dispatcher).to receive(:formatter?).and_return(true)
- expect(event_dispatcher).to receive(:resource_update_progress).with(new_resource, 50, 100, 10).ordered
- expect(event_dispatcher).to receive(:resource_update_progress).with(new_resource, 70, 100, 10).ordered
- fetcher.fetch
- end
- end
-
context "and the response does not contain an etag" do
let(:last_response) { { "etag" => nil } }
it "does not include an etag in the result" do
@@ -290,7 +292,7 @@ describe Chef::Provider::RemoteFile::HTTP do
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
diff --git a/spec/unit/provider/remote_file/local_file_spec.rb b/spec/unit/provider/remote_file/local_file_spec.rb
index 6f345cadd1..6dad6a57f2 100644
--- a/spec/unit/provider/remote_file/local_file_spec.rb
+++ b/spec/unit/provider/remote_file/local_file_spec.rb
@@ -84,8 +84,8 @@ describe Chef::Provider::RemoteFile::LocalFile do
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) }
+ let(:tempfile) { double("Tempfile", path: "/tmp/foo/bar/nyan.png", close: nil) }
+ let(:chef_tempfile) { double("Chef::FileContentManagement::Tempfile", tempfile: tempfile) }
before do
current_resource.source("file:///nyan_cat.png")
diff --git a/spec/unit/provider/remote_file/network_file_spec.rb b/spec/unit/provider/remote_file/network_file_spec.rb
index 621d2769a4..1c2bcc5911 100644
--- a/spec/unit/provider/remote_file/network_file_spec.rb
+++ b/spec/unit/provider/remote_file/network_file_spec.rb
@@ -28,12 +28,12 @@ describe Chef::Provider::RemoteFile::NetworkFile do
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) }
- let(:source_file) { double("::File", :read => nil) }
+ let(:tempfile) { double("Tempfile", path: "/tmp/foo/bar/Foo.tar.gz", close: nil) }
+ let(:chef_tempfile) { double("Chef::FileContentManagement::Tempfile", tempfile: tempfile) }
+ let(:source_file) { double("::File", read: nil) }
before do
- allow(fetcher).to receive(:node).and_return({ "platform_family" => "windows" })
+ allow(Chef::Platform).to receive(:windows?).and_return(true)
end
it "stages the local file to a temporary file" do
diff --git a/spec/unit/provider/remote_file/sftp_spec.rb b/spec/unit/provider/remote_file/sftp_spec.rb
index ddab1605f0..244440d5c3 100644
--- a/spec/unit/provider/remote_file/sftp_spec.rb
+++ b/spec/unit/provider/remote_file/sftp_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
describe Chef::Provider::RemoteFile::SFTP do
- #built out dependencies
+ # built out dependencies
let(:enclosing_directory) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
@@ -120,7 +120,7 @@ describe Chef::Provider::RemoteFile::SFTP do
let(:uri) { URI.parse("sftp://conan:cthu1hu@opscode.com:8021/seattle.txt") }
it "should connect on an alternate port when one is provided" do
- expect(Net::SFTP).to receive(:start).with("opscode.com:8021", "conan", :password => "cthu1hu")
+ expect(Net::SFTP).to receive(:start).with("opscode.com:8021", "conan", password: "cthu1hu")
fetcher.fetch
end
diff --git a/spec/unit/provider/remote_file_spec.rb b/spec/unit/provider/remote_file_spec.rb
index 6ceb1d450d..07b854da6b 100644
--- a/spec/unit/provider/remote_file_spec.rb
+++ b/spec/unit/provider/remote_file_spec.rb
@@ -36,7 +36,8 @@ describe Chef::Provider::RemoteFile do
let(:node) { double("Chef::Node") }
let(:events) { double("Chef::Events").as_null_object } # mock all the methods
- let(:run_context) { double("Chef::RunContext", :node => node, :events => events) }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
let(:enclosing_directory) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
diff --git a/spec/unit/provider/route_spec.rb b/spec/unit/provider/route_spec.rb
index 5e655bda0c..ea6ddffb81 100644
--- a/spec/unit/provider/route_spec.rb
+++ b/spec/unit/provider/route_spec.rb
@@ -236,9 +236,11 @@ describe Chef::Provider::Route do
@node.automatic_attrs[:platform] = platform
route_file = StringIO.new
+ allow(File).to receive(:exist?).with("/etc/sysconfig/network").and_return(false)
expect(File).to receive(:new).with("/etc/sysconfig/network", "w").and_return(route_file)
@run_context.resource_collection << @default_resource
@default_provider.generate_config
+ expect(route_file.string).to match(/GATEWAY=10\.0\.0\.9/)
end
end
diff --git a/spec/unit/provider/script_spec.rb b/spec/unit/provider/script_spec.rb
index 951d6546c3..08b19730a7 100644
--- a/spec/unit/provider/script_spec.rb
+++ b/spec/unit/provider/script_spec.rb
@@ -93,7 +93,7 @@ describe Chef::Provider::Script, "action_run" do
end
context "when an alternate user is specified" do
- let(:security_descriptor) { instance_double("Chef::ReservedNames::Win32::Security::SecurityDescriptor", :dacl => []) }
+ let(:security_descriptor) { instance_double("Chef::ReservedNames::Win32::Security::SecurityDescriptor", dacl: []) }
let(:securable_object) { instance_double("Chef::ReservedNames::Win32::Security::SecurableObject", :security_descriptor => security_descriptor, :dacl= => nil) }
it "sets the script file's security descriptor" do
new_resource.user("toor")
@@ -131,7 +131,7 @@ describe Chef::Provider::Script, "action_run" do
describe "when running the script" do
let (:default_opts) do
- { timeout: 3600, returns: 0, log_level: :info, log_tag: "script[run some perl code]" }
+ { timeout: 3600, returns: 0, default_env: false, log_level: :info, log_tag: "script[run some perl code]" }
end
before do
@@ -143,7 +143,7 @@ describe Chef::Provider::Script, "action_run" do
end
it "should call shell_out! with the command" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with(provider.command, default_opts).and_return(true)
+ expect(provider).to receive(:shell_out!).with(provider.command, default_opts).and_return(true)
provider.action_run
end
diff --git a/spec/unit/provider/service/aix_service_spec.rb b/spec/unit/provider/service/aix_service_spec.rb
index 802ccee2c7..cf6309e82a 100644
--- a/spec/unit/provider/service/aix_service_spec.rb
+++ b/spec/unit/provider/service/aix_service_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Provider::Service::Aix do
describe "load current resource" do
it "should create a current resource with the name of the new resource and determine the status" do
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
expect(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
@@ -47,7 +47,7 @@ describe Chef::Provider::Service::Aix do
describe "determine current status" do
context "when the service is active" do
before do
- @status = double("Status", :exitstatus => 0, :stdout => "chef chef 12345 active\n")
+ @status = double("Status", exitstatus: 0, stdout: "chef chef 12345 active\n")
end
it "current resource is running" do
@@ -61,7 +61,7 @@ describe Chef::Provider::Service::Aix do
context "when the service is inoperative" do
before do
- @status = double("Status", :exitstatus => 0, :stdout => "chef chef inoperative\n")
+ @status = double("Status", exitstatus: 0, stdout: "chef chef inoperative\n")
end
it "current resource is not running" do
@@ -75,7 +75,7 @@ describe Chef::Provider::Service::Aix do
context "when there is no such service" do
before do
- @status = double("Status", :exitstatus => 1, :stdout => "0513-085 The chef Subsystem is not on file.\n")
+ @status = double("Status", exitstatus: 1, stdout: "0513-085 The chef Subsystem is not on file.\n")
end
it "current resource is not running" do
expect(@provider).to receive(:shell_out!).with("lssrc -s chef").and_return(@status)
@@ -90,7 +90,7 @@ describe Chef::Provider::Service::Aix do
describe "is resource group" do
context "when there are multiple subsystems associated with group" do
before do
- @status = double("Status", :exitstatus => 0, :stdout => "chef1 chef 12345 active\nchef2 chef 12334 active\nchef3 chef inoperative")
+ @status = double("Status", exitstatus: 0, stdout: "chef1 chef 12345 active\nchef2 chef 12334 active\nchef3 chef inoperative")
end
it "service is a group" do
@@ -102,7 +102,7 @@ describe Chef::Provider::Service::Aix do
context "when there is a single subsystem in the group" do
before do
- @status = double("Status", :exitstatus => 0, :stdout => "chef1 chef inoperative\n")
+ @status = double("Status", exitstatus: 0, stdout: "chef1 chef inoperative\n")
end
it "service is a group" do
@@ -114,8 +114,8 @@ describe Chef::Provider::Service::Aix do
context "when the service is a subsystem" do
before do
- @group_status = double("Status", :exitstatus => 1, :stdout => "0513-086 The chef Group is not on file.\n")
- @service_status = double("Status", :exitstatus => 0, :stdout => "chef chef inoperative\n")
+ @group_status = double("Status", exitstatus: 1, stdout: "0513-086 The chef Group is not on file.\n")
+ @service_status = double("Status", exitstatus: 0, stdout: "chef chef inoperative\n")
end
it "service is a subsystem" do
diff --git a/spec/unit/provider/service/aixinit_service_spec.rb b/spec/unit/provider/service/aixinit_service_spec.rb
index 09c177903b..6a586a0240 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)
@@ -209,7 +209,7 @@ describe Chef::Provider::Service::AixInit do
before 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 => [:start, 20], 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)
@@ -256,7 +256,7 @@ describe Chef::Provider::Service::AixInit do
before 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 => [:start, ''], 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)
diff --git a/spec/unit/provider/service/arch_service_spec.rb b/spec/unit/provider/service/arch_service_spec.rb
index 010b4a989f..18db25fef9 100644
--- a/spec/unit/provider/service/arch_service_spec.rb
+++ b/spec/unit/provider/service/arch_service_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Jan Zimmek (<jan.zimmek@web.de>)
# Author:: AJ Christensen (<aj@hjksolutions.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -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)
@@ -43,7 +43,7 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
describe "when first created" do
it "should set the current resources service name to the new resources service name" do
- allow(@provider).to receive(:shell_out).and_return(OpenStruct.new(:exitstatus => 0, :stdout => ""))
+ allow(@provider).to receive(:shell_out).and_return(OpenStruct.new(exitstatus: 0, stdout: ""))
@provider.load_current_resource
expect(@provider.current_resource.service_name).to eq("chef")
end
@@ -51,22 +51,22 @@ 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
- expect(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 0))
+ expect(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(exitstatus: 0))
@provider.load_current_resource
end
it "should set running to true if the status command returns 0" do
- allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 0))
+ allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(exitstatus: 0))
@provider.load_current_resource
expect(@provider.current_resource.running).to be_truthy
end
it "should set running to false if the status command returns anything except 0" do
- allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(:exitstatus => 1))
+ allow(@provider).to receive(:shell_out).with("/etc/rc.d/chef status").and_return(OpenStruct.new(exitstatus: 1))
@provider.load_current_resource
expect(@provider.current_resource.running).to be_falsey
end
@@ -85,21 +85,21 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
end
it "should run the services status command if one has been specified" do
- expect(@provider).to receive(:shell_out).with("/etc/rc.d/chefhasmonkeypants status").and_return(OpenStruct.new(:exitstatus => 0))
+ 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)
@@ -117,21 +117,21 @@ describe Chef::Provider::Service::Arch, "load_current_resource" do
describe "when discovering service status with ps" do
before do
- @stdout = StringIO.new(<<-DEFAULT_PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
-aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
-aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
+ @stdout = StringIO.new(<<~DEFAULT_PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
+ aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
+ aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
DEFAULT_PS
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @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
- @stdout = StringIO.new(<<-RUNNING_PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 chef
-aj 7842 5057 0 21:26 pts/2 00:00:06 poos
+ @stdout = StringIO.new(<<~RUNNING_PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 chef
+ aj 7842 5057 0 21:26 pts/2 00:00:06 poos
RUNNING_PS
allow(@status).to receive(:stdout).and_return(@stdout)
@provider.load_current_resource
@@ -222,12 +222,12 @@ RUNNING_PS
it "should call the start command if one is specified" do
@new_resource.start_command("/etc/rc.d/chef startyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/chef startyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
@provider.start_service()
end
it "should call '/etc/rc.d/service_name start' if no start command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} start")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} start", default_env: false)
@provider.start_service()
end
end
@@ -248,12 +248,12 @@ RUNNING_PS
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/rc.d/chef itoldyoutostop")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/chef itoldyoutostop")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/chef itoldyoutostop", default_env: false)
@provider.stop_service()
end
it "should call '/etc/rc.d/service_name stop' if no stop command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} stop")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} stop", default_env: false)
@provider.stop_service()
end
end
@@ -274,14 +274,14 @@ RUNNING_PS
# end
it "should call 'restart' on the service_name if the resource supports it" do
- @new_resource.supports({ :restart => true })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} restart")
+ @new_resource.supports({ restart: true })
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restart", default_env: false)
@provider.restart_service()
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/etc/rc.d/chef restartinafire")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} restartinafire")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} restartinafire", default_env: false)
@provider.restart_service()
end
@@ -309,14 +309,14 @@ RUNNING_PS
# end
it "should call 'reload' on the service if it supports it" do
- @new_resource.supports({ :reload => true })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} reload")
+ @new_resource.supports({ reload: true })
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} reload", default_env: false)
@provider.reload_service()
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/etc/rc.d/chef lollerpants")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{@new_resource.service_name} lollerpants")
+ expect(@provider).to receive(:shell_out!).with("/etc/rc.d/#{@new_resource.service_name} lollerpants", default_env: false)
@provider.reload_service()
end
end
diff --git a/spec/unit/provider/service/debian_service_spec.rb b/spec/unit/provider/service/debian_service_spec.rb
index d944192755..626abb10f7 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)
@@ -32,6 +32,17 @@ describe Chef::Provider::Service::Debian do
@provider.current_resource = @current_resource
@pid, @stdin, @stdout, @stderr = nil, nil, nil, nil
+ allow(File).to receive(:exist?).with("/etc/init.d/chef").and_return true
+ end
+
+ let(:init_lines) do
+ [
+ "### BEGIN INIT INFO",
+ "# Required-Start: hostname $local_fs",
+ "# Default-Start: 2 3 4 5",
+ "# Default-Stop: 0 1 6",
+ "### END INIT INFO",
+ ]
end
describe "load_current_resource" do
@@ -47,22 +58,14 @@ describe Chef::Provider::Service::Debian do
context "when update-rc.d shows init linked to rc*.d/" do
before do
allow(@provider).to receive(:assert_update_rcd_available)
+ allow(File).to receive(:readlines).with("/etc/init.d/chef").and_return(init_lines)
- result = <<-UPDATE_RC_D_SUCCESS
- Removing any system startup links for /etc/init.d/chef ...
- /etc/rc0.d/K20chef
- /etc/rc1.d/K20chef
- /etc/rc2.d/S20chef
- /etc/rc3.d/S20chef
- /etc/rc4.d/S20chef
- /etc/rc5.d/S20chef
- /etc/rc6.d/K20chef
- UPDATE_RC_D_SUCCESS
-
- @stdout = result
- @stderr = ""
- @status = double("Status", :exitstatus => 0, :stdout => @stdout, :stderr => @stderr)
- allow(@provider).to receive(:shell_out!).and_return(@status)
+ [0, 1, 6].each do |stop|
+ allow(Dir).to receive(:glob).with("/etc/rc#{stop}.d/[SK][0-9][0-9]chef").and_return(["/etc/rc#{stop}.d/K20chef"])
+ end
+ [2, 3, 4, 5].each do |start|
+ allow(Dir).to receive(:glob).with("/etc/rc#{start}.d/[SK][0-9][0-9]chef").and_return(["/etc/rc#{start}.d/S20chef"])
+ end
end
it "says the service is enabled" do
@@ -74,14 +77,34 @@ describe Chef::Provider::Service::Debian do
expect(@provider.load_current_resource).to equal(@current_resource)
expect(@current_resource.enabled).to be_truthy
end
+
+ it "stores the start/stop priorities of the service" do
+ @provider.load_current_resource
+ expect(@provider.current_resource.priority).to eq(
+ {
+ "2" => [:start, "20"],
+ "3" => [:start, "20"],
+ "4" => [:start, "20"],
+ "5" => [:start, "20"],
+ "0" => [:stop, "20"],
+ "1" => [:stop, "20"],
+ "6" => [:stop, "20"],
+ })
+ end
end
context "when update-rc.d shows init isn't linked to rc*.d/" do
before do
allow(@provider).to receive(:assert_update_rcd_available)
- @stdout = " Removing any system startup links for /etc/init.d/chef ..."
- @status = double("Status", :exitstatus => 0, :stdout => @stdout, stderr: "")
- allow(@provider).to receive(:shell_out!).and_return(@status)
+
+ allow(File).to receive(:readlines).with("/etc/init.d/chef").and_return(init_lines)
+
+ [0, 1, 6].each do |stop|
+ allow(Dir).to receive(:glob).with("/etc/rc#{stop}.d/[SK][0-9][0-9]chef").and_return([])
+ end
+ [2, 3, 4, 5].each do |start|
+ allow(Dir).to receive(:glob).with("/etc/rc#{start}.d/[SK][0-9][0-9]chef").and_return([])
+ end
end
it "says the service is disabled" do
@@ -95,149 +118,6 @@ describe Chef::Provider::Service::Debian do
end
end
- context "when update-rc.d fails" do
- before do
- @status = double("Status", exitstatus: -1, stdout: "", stderr: "")
- allow(@provider).to receive(:shell_out!).and_return(@status)
- end
-
- it "raises an error" do
- @provider.load_current_resource
- @provider.define_resource_requirements
- expect do
- @provider.process_resource_requirements
- end.to raise_error(Chef::Exceptions::Service)
- end
- end
-
- { "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
- /etc/rc2.d/S20chef
- /etc/rc3.d/S20chef
- /etc/rc4.d/S20chef
- /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" => "",
- },
- },
- "Debian/Squeeze and earlier" => {
- "linked" => {
- "stdout" => "update-rc.d: using dependency based boot sequencing",
- "stderr" => <<-STDERR,
-insserv: remove service /etc/init.d/../rc0.d/K20chef-client
- insserv: remove service /etc/init.d/../rc1.d/K20chef-client
- insserv: remove service /etc/init.d/../rc2.d/S20chef-client
- insserv: remove service /etc/init.d/../rc3.d/S20chef-client
- insserv: remove service /etc/init.d/../rc4.d/S20chef-client
- insserv: remove service /etc/init.d/../rc5.d/S20chef-client
- insserv: remove service /etc/init.d/../rc6.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"],
- },
- },
- "not linked" => {
- "stdout" => "update-rc.d: using dependency based boot sequencing",
- "stderr" => "",
- },
- },
- "Debian/Wheezy and earlier, a service only starting at run level S" => {
- "linked" => {
- "stdout" => "",
- "stderr" => <<-STDERR,
-insserv: remove service /etc/init.d/../rc0.d/K06rpcbind
-insserv: remove service /etc/init.d/../rc1.d/K06rpcbind
-insserv: remove service /etc/init.d/../rc6.d/K06rpcbind
-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"],
- },
- },
- "not linked" => {
- "stdout" => "",
- "stderr" => "insserv: dryrun, not creating .depend.boot, .depend.start, and .depend.stop",
- },
- },
- }.each do |model, expected_results|
- context "on #{model}" do
- context "when update-rc.d shows init linked to rc*.d/" do
- before do
- allow(@provider).to receive(:assert_update_rcd_available)
-
- @stdout = expected_results["linked"]["stdout"]
- @stderr = expected_results["linked"]["stderr"]
- @status = double("Status", exitstatus: 0, stdout: @stdout, stderr: @stderr)
- allow(@provider).to receive(:shell_out!).and_return(@status)
- end
-
- it "says the service is enabled" do
- expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_truthy
- end
-
- it "stores the 'enabled' state" do
- allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- expect(@provider.load_current_resource).to equal(@current_resource)
- expect(@current_resource.enabled).to be_truthy
- end
-
- it "stores the start/stop priorities of the service" do
- @provider.load_current_resource
- expect(@provider.current_resource.priority).to eq(expected_results["linked"]["priorities"])
- end
- end
-
- context "when update-rc.d shows init isn't linked to rc*.d/" do
- before do
- allow(@provider).to receive(:assert_update_rcd_available)
- @stdout = expected_results["not linked"]["stdout"]
- @stderr = expected_results["not linked"]["stderr"]
- @status = double("Status", exitstatus: 0, stdout: @stdout, stderr: @stderr)
- allow(@provider).to receive(:shell_out!).and_return(@status)
- end
-
- it "says the service is disabled" do
- expect(@provider.service_currently_enabled?(@provider.get_priority)).to be_falsey
- end
-
- it "stores the 'disabled' state" do
- allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- expect(@provider.load_current_resource).to equal(@current_resource)
- expect(@current_resource.enabled).to be_falsey
- end
- end
- end
- end
-
end
describe "action_enable" do
diff --git a/spec/unit/provider/service/freebsd_service_spec.rb b/spec/unit/provider/service/freebsd_service_spec.rb
index 10eb3c1a14..954ef3d153 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
@@ -99,7 +99,7 @@ describe Chef::Provider::Service::Freebsd do
end
context "when a status command has been specified" do
- let(:status) { double(:stdout => "", :exitstatus => 0) }
+ let(:status) { double(stdout: "", exitstatus: 0) }
before do
new_resource.status_command("/bin/chefhasmonkeypants status")
@@ -112,10 +112,10 @@ describe Chef::Provider::Service::Freebsd do
end
context "when the service supports status" do
- let(:status) { double(:stdout => "", :exitstatus => 0) }
+ 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
@@ -138,16 +138,16 @@ describe Chef::Provider::Service::Freebsd do
context "when we have a 'ps' attribute" do
let(:stdout) do
- StringIO.new(<<-PS_SAMPLE)
-413 ?? Ss 0:02.51 /usr/sbin/syslogd -s
-539 ?? Is 0:00.14 /usr/sbin/sshd
-545 ?? Ss 0:17.53 sendmail: accepting connections (sendmail)
+ StringIO.new(<<~PS_SAMPLE)
+ 413 ?? Ss 0:02.51 /usr/sbin/syslogd -s
+ 539 ?? Is 0:00.14 /usr/sbin/sshd
+ 545 ?? Ss 0:17.53 sendmail: accepting connections (sendmail)
PS_SAMPLE
end
- let(:status) { double(:stdout => stdout, :exitstatus => 0) }
+ 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
@@ -163,9 +163,9 @@ PS_SAMPLE
context "when the regex matches the output" do
let(:stdout) do
- StringIO.new(<<-PS_SAMPLE)
-555 ?? Ss 0:05.16 /usr/sbin/cron -s
- 9881 ?? Ss 0:06.67 /usr/local/sbin/httpd -DNOHTTPACCEPT
+ StringIO.new(<<~PS_SAMPLE)
+ 555 ?? Ss 0:05.16 /usr/sbin/cron -s
+ 9881 ?? Ss 0:06.67 /usr/local/sbin/httpd -DNOHTTPACCEPT
PS_SAMPLE
end
@@ -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
@@ -341,9 +341,9 @@ PS_SAMPLE
context "when the rc script has a 'name' variable" do
let(:rcscript) do
- StringIO.new(<<-EOF)
-name="#{new_resource.service_name}"
-rcvar=`set_rcvar`
+ StringIO.new(<<~EOF)
+ name="#{new_resource.service_name}"
+ rcvar=`set_rcvar`
EOF
end
@@ -363,23 +363,23 @@ EOF
describe "when the rcscript does not have a name variable" do
let(:rcscript) do
- StringIO.new <<-EOF
-rcvar=`set_rcvar`
+ StringIO.new <<~EOF
+ rcvar=`set_rcvar`
EOF
end
before do
- status = double(:stdout => rcvar_stdout, :exitstatus => 0)
+ status = double(stdout: rcvar_stdout, exitstatus: 0)
allow(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} rcvar").and_return(status)
end
describe "when rcvar returns foobar_enable" do
let(:rcvar_stdout) do
- rcvar_stdout = <<-EOF
-# apache22
-#
-# #{new_resource.service_name}_enable="YES"
-# (default: "")
+ rcvar_stdout = <<~EOF
+ # apache22
+ #
+ # #{new_resource.service_name}_enable="YES"
+ # (default: "")
EOF
end
@@ -394,9 +394,9 @@ EOF
describe "when rcvar does not return foobar_enable" do
let(:rcvar_stdout) do
- rcvar_stdout = <<-EOF
-# service_with_noname
-#
+ rcvar_stdout = <<~EOF
+ # service_with_noname
+ #
EOF
end
@@ -444,12 +444,12 @@ EOF
describe Chef::Provider::Service::Freebsd, "start_service" do
it "should call the start command if one is specified" do
new_resource.start_command("/etc/rc.d/chef startyousillysally")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/chef startyousillysally")
+ expect(provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
provider.start_service()
end
it "should call '/usr/local/etc/rc.d/service_name faststart' if no start command is specified" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststart")
+ expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststart", default_env: false)
provider.start_service()
end
end
@@ -457,26 +457,26 @@ EOF
describe Chef::Provider::Service::Freebsd, "stop_service" do
it "should call the stop command if one is specified" do
new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef itoldyoutostop")
+ expect(provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
provider.stop_service()
end
it "should call '/usr/local/etc/rc.d/service_name faststop' if no stop command is specified" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststop")
+ expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} faststop", default_env: false)
provider.stop_service()
end
end
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 })
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/usr/local/etc/rc.d/#{new_resource.service_name} fastrestart")
+ new_resource.supports({ restart: true })
+ expect(provider).to receive(:shell_out!).with("/usr/local/etc/rc.d/#{new_resource.service_name} fastrestart", default_env: false)
provider.restart_service()
end
it "should call the restart_command if one has been specified" do
new_resource.restart_command("/etc/init.d/chef restartinafire")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef restartinafire")
+ expect(provider).to receive(:shell_out!).with("/etc/init.d/chef restartinafire", default_env: false)
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..6a928d849b 100644
--- a/spec/unit/provider/service/gentoo_service_spec.rb
+++ b/spec/unit/provider/service/gentoo_service_spec.rb
@@ -30,7 +30,7 @@ describe Chef::Provider::Service::Gentoo do
@provider = Chef::Provider::Service::Gentoo.new(@new_resource, @run_context)
allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out).and_return(@status)
allow(File).to receive(:exists?).with("/etc/init.d/chef").and_return(true)
allow(File).to receive(:exists?).with("/sbin/rc-update").and_return(true)
diff --git a/spec/unit/provider/service/init_service_spec.rb b/spec/unit/provider/service/init_service_spec.rb
index 9d53303a76..7bbe2c6363 100644
--- a/spec/unit/provider/service/init_service_spec.rb
+++ b/spec/unit/provider/service/init_service_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: AJ Christensen (<aj@hjksolutions.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -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)
@@ -32,12 +32,12 @@ describe Chef::Provider::Service::Init, "load_current_resource" do
@provider = Chef::Provider::Service::Init.new(@new_resource, @run_context)
allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- @stdout = StringIO.new(<<-PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
-aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
-aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
+ @stdout = StringIO.new(<<~PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
+ aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
+ aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
PS
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
end
@@ -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
@@ -100,7 +100,7 @@ PS
end
it "should use the init_command if one has been specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/opt/chef-server/service/erchef start")
+ expect(@provider).to receive(:shell_out!).with("/opt/chef-server/service/erchef start", default_env: false)
@provider.start_service
end
@@ -109,7 +109,7 @@ PS
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,7 +117,7 @@ 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
@@ -133,9 +133,9 @@ PS
end
it "should set running to true if the regex matches the output" do
- @stdout = StringIO.new(<<-RUNNING_PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 chef
-aj 7842 5057 0 21:26 pts/2 00:00:06 poos
+ @stdout = StringIO.new(<<~RUNNING_PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 chef
+ aj 7842 5057 0 21:26 pts/2 00:00:06 poos
RUNNING_PS
allow(@status).to receive(:stdout).and_return(@stdout)
@provider.load_current_resource
@@ -164,12 +164,12 @@ RUNNING_PS
describe "when starting the service" do
it "should call the start command if one is specified" do
@new_resource.start_command("/etc/init.d/chef startyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef startyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef startyousillysally", default_env: false)
@provider.start_service()
end
it "should call '/etc/init.d/service_name start' if no start command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/#{@new_resource.service_name} start")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} start", default_env: false)
@provider.start_service()
end
end
@@ -177,26 +177,26 @@ RUNNING_PS
describe Chef::Provider::Service::Init, "stop_service" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef itoldyoutostop")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
@provider.stop_service()
end
it "should call '/etc/init.d/service_name stop' if no stop command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/#{@new_resource.service_name} stop")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} stop", default_env: false)
@provider.stop_service()
end
end
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 })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/#{@new_resource.service_name} restart")
+ @new_resource.supports({ restart: true })
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} restart", default_env: false)
@provider.restart_service()
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/etc/init.d/chef restartinafire")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/#{@new_resource.service_name} restartinafire")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/#{@new_resource.service_name} restartinafire", default_env: false)
@provider.restart_service()
end
@@ -210,14 +210,14 @@ 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 })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef reload")
+ @new_resource.supports({ reload: true })
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef reload", default_env: false)
@provider.reload_service()
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/etc/init.d/chef lollerpants")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef lollerpants")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef lollerpants", default_env: false)
@provider.reload_service()
end
end
@@ -225,7 +225,7 @@ RUNNING_PS
describe "when a custom command has been specified" do
before do
@new_resource.start_command("/etc/init.d/chef startyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef startyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/chef startyousillysally", default_env: false)
end
it "should still pass all why run assertions" do
diff --git a/spec/unit/provider/service/insserv_service_spec.rb b/spec/unit/provider/service/insserv_service_spec.rb
index 3b2b19c432..f2fe19db59 100644
--- a/spec/unit/provider/service/insserv_service_spec.rb
+++ b/spec/unit/provider/service/insserv_service_spec.rb
@@ -23,13 +23,13 @@ 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")
@provider = Chef::Provider::Service::Insserv.new(@new_resource, @run_context)
- @status = double("Process::Status mock", :exitstatus => 0, :stdout => "")
+ @status = double("Process::Status mock", exitstatus: 0, stdout: "")
allow(@provider).to receive(:shell_out!).and_return(@status)
end
diff --git a/spec/unit/provider/service/invokercd_service_spec.rb b/spec/unit/provider/service/invokercd_service_spec.rb
index 7a7f1e0831..2e30c16da4 100644
--- a/spec/unit/provider/service/invokercd_service_spec.rb
+++ b/spec/unit/provider/service/invokercd_service_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: AJ Christensen (<aj@hjksolutions.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -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)
@@ -32,12 +32,12 @@ describe Chef::Provider::Service::Invokercd, "load_current_resource" do
@provider = Chef::Provider::Service::Invokercd.new(@new_resource, @run_context)
allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- @stdout = StringIO.new(<<-PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
-aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
-aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
+ @stdout = StringIO.new(<<~PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
+ aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
+ aj 8119 6041 0 21:34 pts/3 00:00:03 vi init_service_spec.rb
PS
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
end
@@ -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
@@ -95,14 +95,14 @@ PS
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)
@@ -112,24 +112,24 @@ PS
describe "when we have a 'ps' attribute" do
it "should shell_out! the node's ps command" do
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
expect(@provider).to receive(:shell_out!).with(@node[:command][:ps]).and_return(@status)
@provider.load_current_resource
end
it "should set running to true if the regex matches the output" do
- @stdout = StringIO.new(<<-RUNNING_PS)
-aj 7842 5057 0 21:26 pts/2 00:00:06 chef
-aj 7842 5057 0 21:26 pts/2 00:00:06 poos
+ @stdout = StringIO.new(<<~RUNNING_PS)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 chef
+ aj 7842 5057 0 21:26 pts/2 00:00:06 poos
RUNNING_PS
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
expect(@provider).to receive(:shell_out!).and_return(@status)
@provider.load_current_resource
expect(@current_resource.running).to be_truthy
end
it "should set running to false if the regex doesn't match" do
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
expect(@provider).to receive(:shell_out!).and_return(@status)
@provider.load_current_resource
expect(@current_resource.running).to be_falsey
@@ -151,12 +151,12 @@ RUNNING_PS
describe "when starting the service" do
it "should call the start command if one is specified" do
@new_resource.start_command("/usr/sbin/invoke-rc.d chef startyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d chef startyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef startyousillysally", default_env: false)
@provider.start_service()
end
it "should call '/usr/sbin/invoke-rc.d service_name start' if no start command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} start")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} start", default_env: false)
@provider.start_service()
end
end
@@ -164,26 +164,26 @@ RUNNING_PS
describe Chef::Provider::Service::Invokercd, "stop_service" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/usr/sbin/invoke-rc.d chef itoldyoutostop")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d chef itoldyoutostop")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef itoldyoutostop", default_env: false)
@provider.stop_service()
end
it "should call '/usr/sbin/invoke-rc.d service_name stop' if no stop command is specified" do
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} stop")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} stop", default_env: false)
@provider.stop_service()
end
end
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 })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restart")
+ @new_resource.supports({ restart: true })
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restart", default_env: false)
@provider.restart_service()
end
it "should call the restart_command if one has been specified" do
@new_resource.restart_command("/usr/sbin/invoke-rc.d chef restartinafire")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restartinafire")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d #{@new_resource.service_name} restartinafire", default_env: false)
@provider.restart_service()
end
@@ -197,14 +197,14 @@ 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 })
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d chef reload")
+ @new_resource.supports({ reload: true })
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef reload", default_env: false)
@provider.reload_service()
end
it "should should run the user specified reload command if one is specified and the service doesn't support reload" do
@new_resource.reload_command("/usr/sbin/invoke-rc.d chef lollerpants")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/usr/sbin/invoke-rc.d chef lollerpants")
+ expect(@provider).to receive(:shell_out!).with("/usr/sbin/invoke-rc.d chef lollerpants", default_env: false)
@provider.reload_service()
end
end
diff --git a/spec/unit/provider/service/macosx_spec.rb b/spec/unit/provider/service/macosx_spec.rb
index 704c7a802e..9864fb0185 100644
--- a/spec/unit/provider/service/macosx_spec.rb
+++ b/spec/unit/provider/service/macosx_spec.rb
@@ -44,18 +44,19 @@ 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(:logger) { double("Mixlib::Log::Child").as_null_object }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
let(:provider) { described_class.new(new_resource, run_context) }
let(:launchctl_stdout) { StringIO.new }
- let(:plutil_stdout) { String.new <<-XML }
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
- <key>Label</key>
- <string>io.redis.redis-server</string>
-</dict>
-</plist>
+ let(:plutil_stdout) { String.new <<~XML }
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ <key>Label</key>
+ <string>io.redis.redis-server</string>
+ </dict>
+ </plist>
XML
%w{Daemon Agent}.each do |service_type|
@@ -73,21 +74,22 @@ XML
end
let(:service_label) { "io.redis.redis-server" }
before do
+ allow(run_context).to receive(:logger).and_return(logger)
allow(Dir).to receive(:glob).and_return([plist], [])
- @stat = double("File::Stat", { :uid => 501 })
+ @stat = double("File::Stat", { uid: 501 })
allow(File).to receive(:stat).and_return(@stat)
- @getpwuid = double("Etc::Passwd", { :name => "mikedodge04" })
+ @getpwuid = double("Etc::Passwd", { name: "mikedodge04" })
allow(Etc).to receive(:getpwuid).and_return(@getpwuid)
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",
- :stdout => launchctl_stdout, :exitstatus => 0))
+ allow(provider).to receive(:shell_out)
+ .with(/(#{su_cmd} '#{cmd}'|#{cmd})/, default_env: false)
+ .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))
+ allow(provider).to receive(:shell_out!)
+ .with(/plutil -convert xml1 -o/, default_env: false)
+ .and_return(double("Status", stdout: plutil_stdout))
end
context "#{service_name} that is a #{service_type} running Osx #{platform_version}" do
@@ -111,9 +113,9 @@ XML
before do
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)
+ allow(provider).to receive(:shell_out!)
+ .with(/plutil -convert xml1 -o/)
+ .and_raise(Mixlib::ShellOut::ShellCommandFailed)
end
it "works for action :nothing" do
@@ -134,20 +136,20 @@ XML
end
context "when launchctl returns pid in service list" do
- let(:launchctl_stdout) { StringIO.new <<-SVC_LIST }
-{
- "LimitLoadToSessionType" = "System";
- "Label" = "io.redis.redis-server";
- "TimeOut" = 30;
- "OnDemand" = false;
- "LastExitStatus" = 0;
- "PID" = 62803;
- "Program" = "do_some.sh";
- "ProgramArguments" = (
- "path/to/do_something.sh";
- "-f";
- );
-};
+ let(:launchctl_stdout) { StringIO.new <<~SVC_LIST }
+ {
+ "LimitLoadToSessionType" = "System";
+ "Label" = "io.redis.redis-server";
+ "TimeOut" = 30;
+ "OnDemand" = false;
+ "LastExitStatus" = 0;
+ "PID" = 62803;
+ "Program" = "do_some.sh";
+ "ProgramArguments" = (
+ "path/to/do_something.sh";
+ "-f";
+ );
+ };
SVC_LIST
before do
@@ -165,7 +167,7 @@ SVC_LIST
describe "running unsupported actions" do
before do
- allow(Dir).to receive(:glob).and_return(["#{plist}"], [])
+ allow(Dir).to receive(:glob).and_return([(plist).to_s], [])
allow(File).to receive(:exists?).and_return([true], [])
end
it "should throw an exception when reload action is attempted" do
@@ -173,19 +175,19 @@ SVC_LIST
end
end
context "when launchctl returns empty service pid" do
- let(:launchctl_stdout) { StringIO.new <<-SVC_LIST }
-{
- "LimitLoadToSessionType" = "System";
- "Label" = "io.redis.redis-server";
- "TimeOut" = 30;
- "OnDemand" = false;
- "LastExitStatus" = 0;
- "Program" = "do_some.sh";
- "ProgramArguments" = (
- "path/to/do_something.sh";
- "-f";
- );
-};
+ let(:launchctl_stdout) { StringIO.new <<~SVC_LIST }
+ {
+ "LimitLoadToSessionType" = "System";
+ "Label" = "io.redis.redis-server";
+ "TimeOut" = 30;
+ "OnDemand" = false;
+ "LastExitStatus" = 0;
+ "Program" = "do_some.sh";
+ "ProgramArguments" = (
+ "path/to/do_something.sh";
+ "-f";
+ );
+ };
SVC_LIST
before do
@@ -202,8 +204,8 @@ SVC_LIST
end
context "when launchctl doesn't return service entry at all" do
- let(:launchctl_stdout) { StringIO.new <<-SVC_LIST }
-Could not find service "io.redis.redis-server" in domain for system
+ let(:launchctl_stdout) { StringIO.new <<~SVC_LIST }
+ Could not find service "io.redis.redis-server" in domain for system
SVC_LIST
it "sets service running state to false" do
@@ -224,7 +226,7 @@ SVC_LIST
context "and plist for service is available" do
before do
- allow(Dir).to receive(:glob).and_return(["#{plist}"], [])
+ allow(Dir).to receive(:glob).and_return([(plist).to_s], [])
provider.load_current_resource
end
@@ -235,7 +237,7 @@ SVC_LIST
describe "and several plists match service name" do
it "throws exception" do
- allow(Dir).to receive(:glob).and_return(["#{plist}",
+ allow(Dir).to receive(:glob).and_return([(plist).to_s,
"/Users/wtf/something.plist"])
provider.load_current_resource
provider.define_resource_requirements
@@ -254,22 +256,22 @@ SVC_LIST
it "calls the start command if one is specified and service is not running" do
allow(new_resource).to receive(:start_command).and_return("cowsay dirty")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("cowsay dirty")
+ expect(provider).to receive(:shell_out!).with("cowsay dirty", default_env: false)
provider.start_service
end
it "shows warning message if service is already running" do
allow(current_resource).to receive(:running).and_return(true)
- expect(Chef::Log).to receive(:debug).with("macosx_service[#{service_name}] already running, not starting")
+ expect(logger).to receive(:trace).with("macosx_service[#{service_name}] already running, not starting")
provider.start_service
end
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)
+ expect(provider).to receive(:shell_out)
+ .with(/(#{su_cmd} .#{cmd}.|#{cmd})/, default_env: false)
+ .and_return(0)
provider.start_service
end
@@ -286,22 +288,22 @@ SVC_LIST
it "calls the stop command if one is specified and service is running" do
allow(new_resource).to receive(:stop_command).and_return("kill -9 123")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("kill -9 123")
+ expect(provider).to receive(:shell_out!).with("kill -9 123", default_env: false)
provider.stop_service
end
it "shows warning message if service is not running" do
allow(current_resource).to receive(:running).and_return(false)
- expect(Chef::Log).to receive(:debug).with("macosx_service[#{service_name}] not running, not stopping")
+ expect(logger).to receive(:trace).with("macosx_service[#{service_name}] not running, not stopping")
provider.stop_service
end
it "stops the service via launchctl if service found" do
cmd = "launchctl unload -w " + plist
- expect(provider).to receive(:shell_out_with_systems_locale).
- with(/(#{su_cmd} .#{cmd}.|#{cmd})/).
- and_return(0)
+ expect(provider).to receive(:shell_out)
+ .with(/(#{su_cmd} .#{cmd}.|#{cmd})/, default_env: false)
+ .and_return(0)
provider.stop_service
end
@@ -319,7 +321,7 @@ SVC_LIST
it "issues a command if given" do
allow(new_resource).to receive(:restart_command).and_return("reload that thing")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("reload that thing")
+ expect(provider).to receive(:shell_out!).with("reload that thing", default_env: false)
provider.restart_service
end
diff --git a/spec/unit/provider/service/openbsd_service_spec.rb b/spec/unit/provider/service/openbsd_service_spec.rb
index 872a3bc400..913fddc1cf 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")
@@ -93,7 +93,7 @@ describe Chef::Provider::Service::Openbsd do
end
context "when a status command has been specified" do
- let(:status) { double(:stdout => "", :exitstatus => 0) }
+ let(:status) { double(stdout: "", exitstatus: 0) }
before do
new_resource.status_command("/bin/chefhasmonkeypants status")
@@ -106,9 +106,9 @@ describe Chef::Provider::Service::Openbsd do
end
context "when the service supports status" do
- let(:status) { double(:stdout => "", :exitstatus => 0) }
+ let(:status) { double(stdout: "", exitstatus: 0) }
- let(:supports) { { :status => true } }
+ let(:supports) { { status: true } }
it "should run '/etc/rc.d/service_name status'" do
expect(provider).to receive(:shell_out).with("/etc/rc.d/#{new_resource.service_name} check").and_return(status)
@@ -189,7 +189,7 @@ describe Chef::Provider::Service::Openbsd do
let(:lines) do
[
%Q{#{provider.builtin_service_enable_variable_name}_thing="YES"},
- %Q{#{provider.builtin_service_enable_variable_name}},
+ (provider.builtin_service_enable_variable_name).to_s,
] end
it "sets enabled based on the exact match (false)" do
provider.determine_enabled_status!
@@ -285,12 +285,12 @@ describe Chef::Provider::Service::Openbsd do
describe Chef::Provider::Service::Openbsd, "start_service" do
it "should call the start command if one is specified" do
new_resource.start_command("/etc/rc.d/chef startyousillysally")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/chef startyousillysally")
+ expect(provider).to receive(:shell_out!).with("/etc/rc.d/chef startyousillysally", default_env: false)
provider.start_service()
end
it "should call '/usr/local/etc/rc.d/service_name start' if no start command is specified" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{new_resource.service_name} start")
+ expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} start", default_env: false)
provider.start_service()
end
end
@@ -298,12 +298,12 @@ describe Chef::Provider::Service::Openbsd do
describe Chef::Provider::Service::Openbsd, "stop_service" do
it "should call the stop command if one is specified" do
new_resource.stop_command("/etc/init.d/chef itoldyoutostop")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef itoldyoutostop")
+ expect(provider).to receive(:shell_out!).with("/etc/init.d/chef itoldyoutostop", default_env: false)
provider.stop_service()
end
it "should call '/usr/local/etc/rc.d/service_name stop' if no stop command is specified" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{new_resource.service_name} stop")
+ expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} stop", default_env: false)
provider.stop_service()
end
end
@@ -312,14 +312,14 @@ describe Chef::Provider::Service::Openbsd do
context "when the new_resource supports restart" do
let(:supports) { { restart: true } }
it "should call 'restart' on the service_name if the resource supports it" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/rc.d/#{new_resource.service_name} restart")
+ expect(provider).to receive(:shell_out!).with("/etc/rc.d/#{new_resource.service_name} restart", default_env: false)
provider.restart_service()
end
end
it "should call the restart_command if one has been specified" do
new_resource.restart_command("/etc/init.d/chef restartinafire")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/chef restartinafire")
+ expect(provider).to receive(:shell_out!).with("/etc/init.d/chef restartinafire", default_env: false)
provider.restart_service()
end
diff --git a/spec/unit/provider/service/redhat_spec.rb b/spec/unit/provider/service/redhat_spec.rb
index 40f9bc3a91..b965183d14 100644
--- a/spec/unit/provider/service/redhat_spec.rb
+++ b/spec/unit/provider/service/redhat_spec.rb
@@ -23,17 +23,17 @@ 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)
end
it "should not raise an error if the service exists but is not added to any runlevels" do
- status = double("Status", :exitstatus => 0, :stdout => "" , :stderr => "")
+ 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)
+ 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)
@provider.load_current_resource
@provider.define_resource_requirements
expect { @provider.process_resource_requirements }.not_to raise_error
@@ -44,7 +44,7 @@ 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)
@@ -65,13 +65,13 @@ describe "Chef::Provider::Service::Redhat" do
describe "load current resource" do
before do
- status = double("Status", :exitstatus => 0, :stdout => "" , :stderr => "")
+ status = double("Status", exitstatus: 0, stdout: "" , stderr: "")
allow(@provider).to receive(:shell_out).with("/sbin/service chef status").and_return(status)
end
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)
+ 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.service_missing).to be false
@provider.load_current_resource
expect(@provider.supports[:status]).to be true
@@ -80,9 +80,9 @@ describe "Chef::Provider::Service::Redhat" do
it "lets the user override supports[:status] in the new_resource" 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)
- foo_out = double("ps_command", :exitstatus => 0, :stdout => "a line that matches myservice", :stderr => "")
+ 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)
+ 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
expect(@provider).not_to receive(:shell_out).with("/sbin/service chef status")
@@ -91,16 +91,16 @@ describe "Chef::Provider::Service::Redhat" do
end
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)
+ 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.service_missing).to be false
@provider.load_current_resource
expect(@current_resource.enabled).to be true
end
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)
+ 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.service_missing).to be false
expect(@provider.load_current_resource).to eql(@current_resource)
expect(@current_resource.enabled).to be false
@@ -108,8 +108,8 @@ 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)
+ 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.service_missing).to be false
@provider.load_current_resource
expect(@current_resource.enabled).to be true
@@ -118,8 +118,8 @@ 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)
+ 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.service_missing).to be false
@provider.load_current_resource
expect(@current_resource.enabled).to be false
@@ -128,8 +128,8 @@ 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)
+ 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.service_missing).to be false
@provider.load_current_resource
expect(@current_resource.enabled).to be false
@@ -142,10 +142,10 @@ describe "Chef::Provider::Service::Redhat" do
context "when the service does not exist" do
before do
- status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service")
+ 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
@@ -194,10 +194,10 @@ describe "Chef::Provider::Service::Redhat" do
it_should_behave_like "define_resource_requirements_common"
it "should not raise an error if the service does not exist" do
- status = double("Status", :exitstatus => 1, :stdout => "", :stderr => "chef: unrecognized service")
+ 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
diff --git a/spec/unit/provider/service/simple_service_spec.rb b/spec/unit/provider/service/simple_service_spec.rb
index 1fdae83dad..0529462d2f 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)
@@ -31,12 +31,12 @@ describe Chef::Provider::Service::Simple, "load_current_resource" do
@provider = Chef::Provider::Service::Simple.new(@new_resource, @run_context)
allow(Chef::Resource::Service).to receive(:new).and_return(@current_resource)
- @stdout = StringIO.new(<<-NOMOCKINGSTRINGSPLZ)
-aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
-aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
-aj 8119 6041 0 21:34 pts/3 00:00:03 vi simple_service_spec.rb
+ @stdout = StringIO.new(<<~NOMOCKINGSTRINGSPLZ)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 vi init.rb
+ aj 7903 5016 0 21:26 pts/5 00:00:00 /bin/bash
+ aj 8119 6041 0 21:34 pts/3 00:00:03 vi simple_service_spec.rb
NOMOCKINGSTRINGSPLZ
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
end
@@ -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
@@ -75,11 +75,11 @@ NOMOCKINGSTRINGSPLZ
end
it "should set running to true if the regex matches the output" do
- @stdout = StringIO.new(<<-NOMOCKINGSTRINGSPLZ)
-aj 7842 5057 0 21:26 pts/2 00:00:06 chef
-aj 7842 5057 0 21:26 pts/2 00:00:06 poos
+ @stdout = StringIO.new(<<~NOMOCKINGSTRINGSPLZ)
+ aj 7842 5057 0 21:26 pts/2 00:00:06 chef
+ aj 7842 5057 0 21:26 pts/2 00:00:06 poos
NOMOCKINGSTRINGSPLZ
- @status = double("Status", :exitstatus => 0, :stdout => @stdout)
+ @status = double("Status", exitstatus: 0, stdout: @stdout)
allow(@provider).to receive(:shell_out!).and_return(@status)
@provider.load_current_resource
expect(@current_resource.running).to be_truthy
@@ -106,8 +106,8 @@ NOMOCKINGSTRINGSPLZ
describe "when starting the service" do
it "should call the start command if one is specified" do
- @new_resource.start_command("#{@new_resource.start_command}")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("#{@new_resource.start_command}")
+ @new_resource.start_command((@new_resource.start_command).to_s)
+ expect(@provider).to receive(:shell_out!).with((@new_resource.start_command).to_s, default_env: false)
@provider.start_service()
end
@@ -121,7 +121,7 @@ NOMOCKINGSTRINGSPLZ
describe "when stopping a service" do
it "should call the stop command if one is specified" do
@new_resource.stop_command("/etc/init.d/themadness stop")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/themadness stop")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/themadness stop", default_env: false)
@provider.stop_service()
end
@@ -135,7 +135,7 @@ NOMOCKINGSTRINGSPLZ
describe Chef::Provider::Service::Simple, "restart_service" do
it "should call the restart command if one has been specified" do
@new_resource.restart_command("/etc/init.d/foo restart")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/etc/init.d/foo restart")
+ expect(@provider).to receive(:shell_out!).with("/etc/init.d/foo restart", default_env: false)
@provider.restart_service()
end
@@ -162,7 +162,7 @@ NOMOCKINGSTRINGSPLZ
it "should should run the user specified reload command if one is specified" do
@new_resource.reload_command("kill -9 1")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("kill -9 1")
+ expect(@provider).to receive(:shell_out!).with("kill -9 1", default_env: false)
@provider.reload_service()
end
end
diff --git a/spec/unit/provider/service/solaris_smf_service_spec.rb b/spec/unit/provider/service/solaris_smf_service_spec.rb
index 584176b944..7b8bd950d2 100644
--- a/spec/unit/provider/service/solaris_smf_service_spec.rb
+++ b/spec/unit/provider/service/solaris_smf_service_spec.rb
@@ -74,19 +74,19 @@ describe Chef::Provider::Service::Solaris do
].join("\n")
# shell_out! return value for a service that is running
- @enabled_svc_status = double("Status", :exitstatus => 0, :stdout => enabled_svc_stdout, :stdin => "", :stderr => "")
+ @enabled_svc_status = double("Status", exitstatus: 0, stdout: enabled_svc_stdout, stdin: "", stderr: "")
# shell_out! return value for a service that is disabled
- @disabled_svc_status = double("Status", :exitstatus => 0, :stdout => disabled_svc_stdout, :stdin => "", :stderr => "")
+ @disabled_svc_status = double("Status", exitstatus: 0, stdout: disabled_svc_stdout, stdin: "", stderr: "")
# shell_out! return value for a service that is in maintenance mode
- @maintenance_svc_status = double("Status", :exitstatus => 0, :stdout => maintenance_svc_stdout, :stdin => "", :stderr => "")
+ @maintenance_svc_status = double("Status", exitstatus: 0, stdout: maintenance_svc_stdout, stdin: "", stderr: "")
# shell_out! return value for a service that does not exist
- @no_svc_status = double("Status", :exitstatus => 1, :stdout => "", :stdin => "", :stderr => "svcs: Pattern 'chef' doesn't match any instances\n")
+ @no_svc_status = double("Status", exitstatus: 1, stdout: "", stdin: "", stderr: "svcs: Pattern 'chef' doesn't match any instances\n")
# shell_out! return value for a successful execution
- @success = double("clear", :exitstatus => 0, :stdout => "", :stdin => "", :stderr => "")
+ @success = double("clear", exitstatus: 0, stdout: "", stdin: "", stderr: "")
end
it "should raise an error if /bin/svcs and /usr/sbin/svcadm are not executable" do
@@ -116,18 +116,19 @@ 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)
+ expect(@provider.maintenance).to be_falsey
@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 +163,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!).twice.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 +173,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!).twice.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 +183,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!).twice.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 +192,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
@@ -205,7 +206,7 @@ describe Chef::Provider::Service::Solaris do
it "should call svcadm enable -s -r chef" do
@new_resource.options("-r")
- 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!).twice.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", "-r", @current_resource.service_name).and_return(@success)
@provider.load_current_resource
@@ -215,7 +216,7 @@ describe Chef::Provider::Service::Solaris do
it "should call svcadm enable -s -r -t chef when passed an array of options" do
@new_resource.options(["-r", "-t"])
- 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!).twice.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", "-r", "-t", @current_resource.service_name).and_return(@success)
@provider.load_current_resource
@@ -231,7 +232,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
@@ -239,7 +240,7 @@ 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.disable_service).to be_truthy
@@ -248,7 +249,7 @@ describe Chef::Provider::Service::Solaris do
it "should call svcadm disable chef with options" do
@new_resource.options("-t")
- 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", "-t", "chef").and_return(@success)
@provider.load_current_resource
expect(@provider.disable_service).to be_truthy
@@ -260,7 +261,7 @@ describe Chef::Provider::Service::Solaris do
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
@@ -273,7 +274,7 @@ describe Chef::Provider::Service::Solaris do
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
diff --git a/spec/unit/provider/service/systemd_service_spec.rb b/spec/unit/provider/service/systemd_service_spec.rb
index cbd8e88022..15b79922b0 100644
--- a/spec/unit/provider/service/systemd_service_spec.rb
+++ b/spec/unit/provider/service/systemd_service_spec.rb
@@ -1,7 +1,7 @@
#
# Author:: Stephen Haynes (<sh@nomitor.com>)
# Author:: Davide Cavalca (<dcavalca@fb.com>)
-# Copyright:: Copyright 2011-2016, Chef Software Inc.
+# Copyright:: Copyright 2011-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,16 +21,7 @@ require "spec_helper"
describe Chef::Provider::Service::Systemd do
- let(:node) do
- node = Chef::Node.new
- node.default["etc"] = Hash.new
- node.default["etc"]["passwd"] = {
- "joe" => {
- "uid" => 10000,
- },
- }
- node
- end
+ let(:node) { Chef::Node.new }
let(:events) { Chef::EventDispatch::Dispatcher.new }
@@ -45,17 +36,18 @@ describe Chef::Provider::Service::Systemd do
let(:provider) { Chef::Provider::Service::Systemd.new(new_resource, run_context) }
let(:shell_out_success) do
- double("shell_out_with_systems_locale", :exitstatus => 0, :error? => false)
+ double("shell_out", exitstatus: 0, error?: false)
end
let(:shell_out_failure) do
- double("shell_out_with_systems_locale", :exitstatus => 1, :error? => true)
+ double("shell_out", exitstatus: 1, error?: true)
end
let(:current_resource) { Chef::Resource::Service.new(service_name) }
before(:each) do
allow(Chef::Resource::Service).to receive(:new).with(service_name).and_return(current_resource)
+ allow(Etc).to receive(:getpwnam).and_return(OpenStruct.new(uid: 10000))
end
describe "load_current_resource" do
@@ -178,19 +170,19 @@ describe Chef::Provider::Service::Systemd 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")
+ expect(provider).to receive(:shell_out!).with("/sbin/rsyslog startyousillysally", default_env: false)
provider.start_service
end
context "when a user is not specified" do
it "should call '#{systemctl_path} --system start service_name' if no start command is specified" do
- expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system start #{service_name_escaped}", {}).and_return(shell_out_success)
+ expect(provider).to receive(:shell_out!).with("#{systemctl_path} --system start #{service_name_escaped}", default_env: false).and_return(shell_out_success)
provider.start_service
end
it "should not call '#{systemctl_path} --system start service_name' if it is already running" do
current_resource.running(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system start #{service_name_escaped}", {})
+ expect(provider).not_to receive(:shell_out!).with("#{systemctl_path} --system start #{service_name_escaped}", {})
provider.start_service
end
end
@@ -198,14 +190,14 @@ describe Chef::Provider::Service::Systemd do
context "when a user is specified" do
it "should call '#{systemctl_path} --user start service_name' if no start command is specified" do
current_resource.user("joe")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --user start #{service_name_escaped}", { :environment => { "DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/10000/bus" }, :user => "joe" }).and_return(shell_out_success)
+ expect(provider).to receive(:shell_out!).with("#{systemctl_path} --user start #{service_name_escaped}", { environment: { "DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/10000/bus" }, user: "joe", default_env: false }).and_return(shell_out_success)
provider.start_service
end
it "should not call '#{systemctl_path} --user start service_name' if it is already running" do
current_resource.running(true)
current_resource.user("joe")
- expect(provider).not_to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --user start #{service_name_escaped}", { :environment => { "DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/10000/bus" }, :user => "joe" })
+ expect(provider).not_to receive(:shell_out!).with("#{systemctl_path} --user start #{service_name_escaped}", { environment: { "DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/10000/bus" }, user: "joe" })
provider.start_service
end
end
@@ -213,13 +205,13 @@ describe Chef::Provider::Service::Systemd do
it "should call the restart command if one is specified" do
current_resource.running(true)
allow(new_resource).to receive(:restart_command).and_return("/sbin/rsyslog restartyousillysally")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog restartyousillysally")
+ expect(provider).to receive(:shell_out!).with("/sbin/rsyslog restartyousillysally", default_env: false)
provider.restart_service
end
it "should call '#{systemctl_path} --system restart service_name' if no restart command is specified" do
current_resource.running(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system restart #{service_name_escaped}", {}).and_return(shell_out_success)
+ expect(provider).to receive(:shell_out!).with("#{systemctl_path} --system restart #{service_name_escaped}", default_env: false).and_return(shell_out_success)
provider.restart_service
end
@@ -228,7 +220,7 @@ describe Chef::Provider::Service::Systemd do
it "should call the reload command" do
current_resource.running(true)
allow(new_resource).to receive(:reload_command).and_return("/sbin/rsyslog reloadyousillysally")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog reloadyousillysally")
+ expect(provider).to receive(:shell_out!).with("/sbin/rsyslog reloadyousillysally", default_env: false)
provider.reload_service
end
end
@@ -236,7 +228,7 @@ describe Chef::Provider::Service::Systemd do
context "when a reload command is not specified" do
it "should call '#{systemctl_path} --system reload service_name' if the service is running" do
current_resource.running(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system reload #{service_name_escaped}", {}).and_return(shell_out_success)
+ expect(provider).to receive(:shell_out!).with("#{systemctl_path} --system reload #{service_name_escaped}", default_env: false).and_return(shell_out_success)
provider.reload_service
end
@@ -251,19 +243,19 @@ describe Chef::Provider::Service::Systemd do
it "should call the stop command if one is specified" do
current_resource.running(true)
allow(new_resource).to receive(:stop_command).and_return("/sbin/rsyslog stopyousillysally")
- expect(provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog stopyousillysally")
+ expect(provider).to receive(:shell_out!).with("/sbin/rsyslog stopyousillysally", default_env: false)
provider.stop_service
end
it "should call '#{systemctl_path} --system stop service_name' if no stop command is specified" do
current_resource.running(true)
- expect(provider).to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system stop #{service_name_escaped}", {}).and_return(shell_out_success)
+ expect(provider).to receive(:shell_out!).with("#{systemctl_path} --system stop #{service_name_escaped}", default_env: false).and_return(shell_out_success)
provider.stop_service
end
it "should not call '#{systemctl_path} --system stop service_name' if it is already stopped" do
current_resource.running(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!).with("#{systemctl_path} --system stop #{service_name_escaped}", {})
+ expect(provider).not_to receive(:shell_out!).with("#{systemctl_path} --system stop #{service_name_escaped}", {})
provider.stop_service
end
end
@@ -272,7 +264,7 @@ describe Chef::Provider::Service::Systemd do
before(:each) do
provider.current_resource = current_resource
current_resource.service_name(service_name)
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
it "should call '#{systemctl_path} --system enable service_name' to enable the service" do
@@ -290,7 +282,7 @@ describe Chef::Provider::Service::Systemd do
before(:each) do
provider.current_resource = current_resource
current_resource.service_name(service_name)
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
it "should call '#{systemctl_path} --system mask service_name' to mask the service" do
@@ -308,7 +300,7 @@ describe Chef::Provider::Service::Systemd do
before(:each) do
provider.current_resource = current_resource
current_resource.service_name(service_name)
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
it "should return true if '#{systemctl_path} --system is-active service_name' returns 0" do
@@ -326,7 +318,7 @@ describe Chef::Provider::Service::Systemd do
before(:each) do
provider.current_resource = current_resource
current_resource.service_name(service_name)
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
it "should return true if '#{systemctl_path} --system is-enabled service_name' returns 0" do
@@ -344,26 +336,26 @@ describe Chef::Provider::Service::Systemd do
before(:each) do
provider.current_resource = current_resource
current_resource.service_name(service_name)
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
it "should return true if '#{systemctl_path} --system is-enabled service_name' returns 'masked' and returns anything except 0" do
- expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(:stdout => "masked", :exitstatus => shell_out_failure))
+ expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(stdout: "masked", exitstatus: shell_out_failure))
expect(provider.is_masked?).to be true
end
it "should return true if '#{systemctl_path} --system is-enabled service_name' outputs 'masked-runtime' and returns anything except 0" do
- expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(:stdout => "masked-runtime", :exitstatus => shell_out_failure))
+ expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(stdout: "masked-runtime", exitstatus: shell_out_failure))
expect(provider.is_masked?).to be true
end
it "should return false if '#{systemctl_path} --system is-enabled service_name' returns 0" do
- expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(:stdout => "enabled", :exitstatus => shell_out_success))
+ expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(stdout: "enabled", exitstatus: shell_out_success))
expect(provider.is_masked?).to be false
end
it "should return false if '#{systemctl_path} --system is-enabled service_name' returns anything except 0 and outputs an error'" do
- expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(:stdout => "Failed to get unit file state for #{service_name}: No such file or directory", :exitstatus => shell_out_failure))
+ expect(provider).to receive(:shell_out).with("#{systemctl_path} --system is-enabled #{service_name_escaped}", {}).and_return(double(stdout: "Failed to get unit file state for #{service_name}: No such file or directory", exitstatus: shell_out_failure))
expect(provider.is_masked?).to be false
end
end
diff --git a/spec/unit/provider/service/upstart_service_spec.rb b/spec/unit/provider/service/upstart_service_spec.rb
index d6ecfc2c43..365201cb38 100644
--- a/spec/unit/provider/service/upstart_service_spec.rb
+++ b/spec/unit/provider/service/upstart_service_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Provider::Service::Upstart do
let(:shell_out_success) do
- double("shell_out_with_systems_locale", :exitstatus => 0, :error? => false)
+ double("shell_out", exitstatus: 0, error?: false)
end
before(:each) do
@@ -43,7 +43,7 @@ describe Chef::Provider::Service::Upstart do
it "should return /etc/event.d as the upstart job directory when running on Ubuntu 9.04" do
@node.automatic_attrs[:platform_version] = "9.04"
- #Chef::Platform.stub(:find_platform_and_version).and_return([ "ubuntu", "9.04" ])
+ # Chef::Platform.stub(:find_platform_and_version).and_return([ "ubuntu", "9.04" ])
@provider = Chef::Provider::Service::Upstart.new(@new_resource, @run_context)
expect(@provider.instance_variable_get(:@upstart_job_dir)).to eq("/etc/event.d")
expect(@provider.instance_variable_get(:@upstart_conf_suffix)).to eq("")
@@ -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)
@@ -167,14 +167,14 @@ describe Chef::Provider::Service::Upstart do
end
it "should set enabled to true when it finds 'starts on'" do
- @lines = double("start on filesystem", :gets => "start on filesystem")
+ @lines = double("start on filesystem", gets: "start on filesystem")
allow(::File).to receive(:open).and_yield(@lines)
expect(@current_resource).to receive(:running).with(false)
@provider.load_current_resource
end
it "should set enabled to false when it finds '#starts on'" do
- @lines = double("start on filesystem", :gets => "#start on filesystem")
+ @lines = double("start on filesystem", gets: "#start on filesystem")
allow(::File).to receive(:open).and_yield(@lines)
expect(@current_resource).to receive(:running).with(false)
@provider.load_current_resource
@@ -267,19 +267,19 @@ describe Chef::Provider::Service::Upstart do
it "should call the start command if one is specified" do
@provider.upstart_service_running = false
@new_resource.start_command("/sbin/rsyslog startyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog startyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog startyousillysally", default_env: false)
@provider.start_service()
end
it "should call '/sbin/start service_name' if no start command is specified" do
@provider.upstart_service_running = false
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/start #{@new_resource.service_name}").and_return(shell_out_success)
+ expect(@provider).to receive(:shell_out!).with("/sbin/start #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
@provider.start_service()
end
it "should not call '/sbin/start service_name' if it is already running" do
@provider.upstart_service_running = true
- expect(@provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(@provider).not_to receive(:shell_out!)
@provider.start_service()
end
@@ -288,14 +288,14 @@ describe Chef::Provider::Service::Upstart do
@new_resource.parameters({ "OSD_ID" => "2" })
@provider = Chef::Provider::Service::Upstart.new(@new_resource, @run_context)
@provider.current_resource = @current_resource
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/start rsyslog OSD_ID=2").and_return(shell_out_success)
+ expect(@provider).to receive(:shell_out!).with("/sbin/start rsyslog OSD_ID=2", default_env: false).and_return(shell_out_success)
@provider.start_service()
end
it "should call the restart command if one is specified" do
allow(@current_resource).to receive(:running).and_return(true)
@new_resource.restart_command("/sbin/rsyslog restartyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog restartyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog restartyousillysally", default_env: false)
@provider.restart_service()
end
@@ -310,40 +310,40 @@ describe Chef::Provider::Service::Upstart do
it "should call '/sbin/start service_name' if restart_service is called for a stopped service" do
@provider.upstart_service_running = false
allow(@current_resource).to receive(:running).and_return(false)
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/start #{@new_resource.service_name}").and_return(shell_out_success)
+ expect(@provider).to receive(:shell_out!).with("/sbin/start #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
@provider.restart_service()
end
it "should call the reload command if one is specified" do
allow(@current_resource).to receive(:running).and_return(true)
@new_resource.reload_command("/sbin/rsyslog reloadyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog reloadyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog reloadyousillysally", default_env: false)
@provider.reload_service()
end
it "should call '/sbin/reload service_name' if no reload command is specified" do
allow(@current_resource).to receive(:running).and_return(true)
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/reload #{@new_resource.service_name}").and_return(shell_out_success)
+ expect(@provider).to receive(:shell_out!).with("/sbin/reload #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
@provider.reload_service()
end
it "should call the stop command if one is specified" do
@provider.upstart_service_running = true
@new_resource.stop_command("/sbin/rsyslog stopyousillysally")
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog stopyousillysally")
+ expect(@provider).to receive(:shell_out!).with("/sbin/rsyslog stopyousillysally", default_env: false)
@provider.stop_service()
end
it "should call '/sbin/stop service_name' if no stop command is specified" do
@provider.upstart_service_running = true
- expect(@provider).to receive(:shell_out_with_systems_locale!).with("/sbin/stop #{@new_resource.service_name}").and_return(shell_out_success)
+ expect(@provider).to receive(:shell_out!).with("/sbin/stop #{@new_resource.service_name}", default_env: false).and_return(shell_out_success)
@provider.stop_service()
end
it "should not call '/sbin/stop service_name' if it is already stopped" do
@provider.upstart_service_running = false
allow(@current_resource).to receive(:running).and_return(false)
- expect(@provider).not_to receive(:shell_out_with_systems_locale!).with("/sbin/stop #{@new_resource.service_name}")
+ expect(@provider).not_to receive(:shell_out!).with("/sbin/stop #{@new_resource.service_name}", default_env: false)
@provider.stop_service()
expect(@upstart_service_running).to be_falsey
end
diff --git a/spec/unit/provider/service/windows_spec.rb b/spec/unit/provider/service/windows_spec.rb
index d4c451511d..1b7f91df76 100644
--- a/spec/unit/provider/service/windows_spec.rb
+++ b/spec/unit/provider/service/windows_spec.rb
@@ -18,18 +18,73 @@
#
require "spec_helper"
-require "mixlib/shellout"
-describe Chef::Provider::Service::Windows, "load_current_resource" do
+describe Chef::Provider::Service::Windows, "load_current_resource", :windows_only do
include_context "Win32"
- let(:new_resource) { Chef::Resource::WindowsService.new("chef") }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
+ let(:chef_service_name) { "chef-client" }
+ let(:new_resource) { Chef::Resource::WindowsService.new(chef_service_name) }
+
+ # Actual response from Win32::Service.config_info('chef-client')
+ let(:chef_service_binary_path_name) do
+ 'C:\\opscode\\chef\\embedded\\bin\\ruby.exe C:\\opscode\\chef\\bin\\chef-windows-service'
+ end
+ let(:chef_service_config_info) do
+ double("Struct::ServiceConfigInfo",
+ service_type: "own process",
+ start_type: "auto start",
+ error_control: "ignore",
+ binary_path_name: chef_service_binary_path_name,
+ load_order_group: "",
+ tag_id: 0,
+ dependencies: ["Winmgmt"],
+ service_start_name: "LocalSystem",
+ display_name: "Chef Client Service"
+ )
+ end
+
+ # Actual response from Win32::Service.services
+ let(:chef_service_info) do
+ double("Struct::ServiceInfo",
+ service_name: chef_service_name,
+ display_name: "Chef Client Service",
+ service_type: "own process",
+ current_state: "running",
+ controls_accepted: [],
+ win32_exit_code: 1077,
+ service_specific_exit_code: 0,
+ check_point: 0,
+ wait_hint: 0,
+ binary_path_name: chef_service_binary_path_name,
+ start_type: "auto start",
+ error_control: "ignore",
+ load_order_group: "",
+ tag_id: 0,
+ start_name: "LocalSystem",
+ dependencies: ["Winmgmt"],
+ description: "Runs Chef Client on regular, configurable intervals.",
+ interactive: false,
+ pid: 0,
+ service_flags: 0,
+ reset_period: 0,
+ reboot_message: nil,
+ command: nil,
+ num_actions: 0,
+ actions: nil,
+ delayed_start: 1
+ )
+ end
+
let(:provider) do
- prvdr = Chef::Provider::Service::Windows.new(new_resource,
- Chef::RunContext.new(Chef::Node.new, {}, Chef::EventDispatch::Dispatcher.new))
+ run_context = Chef::RunContext.new(Chef::Node.new, {}, Chef::EventDispatch::Dispatcher.new)
+ allow(run_context).to receive(:logger).and_return(logger)
+ prvdr = Chef::Provider::Service::Windows.new(new_resource, run_context)
prvdr.current_resource = Chef::Resource::WindowsService.new("current-chef")
prvdr
end
+
let(:service_right) { Chef::Provider::Service::Windows::SERVICE_RIGHT }
before(:all) do
@@ -42,12 +97,36 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
Win32::Service::DISABLED = 0x00000004
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "running"))
- allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "auto start"))
+ double("StatusStruct", current_state: "running"))
+ allow(Win32::Service).to receive(:config_info).with(new_resource.service_name)
+ .and_return(chef_service_config_info)
+
+ # Real response from Win32::Service.services
+ allow(Win32::Service).to receive(:services).and_return([
+ # Add chef_service_info to our stubbed response so our tests that are expecting the service to exist work
+ chef_service_info,
+ double("Struct::ServiceInfo", service_name: "ACPI", display_name: "Microsoft ACPI Driver", service_type: "kernel driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: '\\SystemRoot\\System32\\drivers\\ACPI.sys', start_type: "boot start", error_control: "critical", load_order_group: "Core", tag_id: 2, start_name: "", dependencies: [], description: "", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "cdrom", display_name: "CD-ROM Driver", service_type: "kernel driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: '\\SystemRoot\\System32\\drivers\\cdrom.sys', start_type: "system start", error_control: "normal", load_order_group: "SCSI CDROM Class", tag_id: 3, start_name: "", dependencies: [], description: "", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "CryptSvc", display_name: "Cryptographic Services", service_type: "share process", current_state: "running", controls_accepted: ["shutdown", "stop", "session change"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k NetworkService', start_type: "auto start", error_control: "normal", load_order_group: "", tag_id: 0, start_name: 'NT Authority\\NetworkService', dependencies: ["RpcSs"], description: "Provides three management services: Catalog Database Service, which confirms the signatures of Windows files and allows new programs to be installed; Protected Root Service, which adds and removes Trusted Root Certification Authority certificates from this computer; and Automatic Root Certificate Update Service, which retrieves root certificates from Windows Update and enable scenarios such as SSL. If this service is stopped, these management services will not function properly. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 932, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 60000 }, 2 => { action_type: "none", delay: 0 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "DcomLaunch", display_name: "DCOM Server Process Launcher", service_type: "share process", current_state: "running", controls_accepted: ["session change"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k DcomLaunch', start_type: "auto start", error_control: "normal", load_order_group: "COM Infrastructure", tag_id: 0, start_name: "LocalSystem", dependencies: [], description: "The DCOMLAUNCH service launches COM and DCOM servers in response to object activation requests. If this service is stopped or disabled, programs using COM or DCOM will not function properly. It is strongly recommended that you have the DCOMLAUNCH service running.", interactive: false, pid: 552, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 1, actions: { 1 => { action_type: "reboot", delay: 60000 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "Dfsc", display_name: "DFS Namespace Client Driver", service_type: "file system driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'System32\\Drivers\\dfsc.sys', start_type: "system start", error_control: "normal", load_order_group: "Network", tag_id: 0, start_name: "", dependencies: ["Mup"], description: "Client driver for access to DFS Namespaces", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "Dhcp", display_name: "DHCP Client", service_type: "share process", current_state: "running", controls_accepted: %w{shutdown stop}, win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalServiceNetworkRestricted', start_type: "auto start", error_control: "normal", load_order_group: "TDI", tag_id: 0, start_name: 'NT Authority\\LocalService', dependencies: %w{NSI Tdx Afd}, description: "Registers and updates IP addresses and DNS records for this computer. If this service is stopped, this computer will not receive dynamic IP addresses and DNS updates. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 780, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 120000 }, 2 => { action_type: "restart", delay: 300000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "EventLog", display_name: "Windows Event Log", service_type: "share process", current_state: "running", controls_accepted: %w{shutdown stop}, win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\System32\\svchost.exe -k LocalServiceNetworkRestricted', start_type: "auto start", error_control: "normal", load_order_group: "Event Log", tag_id: 0, start_name: 'NT AUTHORITY\\LocalService', dependencies: [], description: "This service manages events and event logs. It supports logging events, querying events, subscribing to events, archiving event logs, and managing event metadata. It can display events in both XML and plain text format. Stopping this service may compromise security and reliability of the system.", interactive: false, pid: 780, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 60000 }, 2 => { action_type: "restart", delay: 120000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "EventSystem", display_name: "COM+ Event System", service_type: "share process", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalService', start_type: "auto start", error_control: "normal", load_order_group: "", tag_id: 0, start_name: 'NT AUTHORITY\\LocalService', dependencies: ["rpcss"], description: "Supports System Event Notification Service (SENS), which provides automatic distribution of events to subscribing Component Object Model (COM) components. If the service is stopped, SENS will close and will not be able to provide logon and logoff notifications. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 844, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 1000 }, 2 => { action_type: "restart", delay: 5000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "LanmanWorkstation", display_name: "Workstation", service_type: "share process", current_state: "running", controls_accepted: ["pause continue", "stop", "power event"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\System32\\svchost.exe -k NetworkService', start_type: "auto start", error_control: "normal", load_order_group: "NetworkProvider", tag_id: 0, start_name: 'NT AUTHORITY\\NetworkService', dependencies: %w{Bowser MRxSmb20 NSI}, description: "Creates and maintains client network connections to remote servers using the SMB protocol. If this service is stopped, these connections will be unavailable. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 932, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 60000 }, 2 => { action_type: "restart", delay: 120000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "lmhosts", display_name: "TCP/IP NetBIOS Helper", service_type: "share process", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalServiceNetworkRestricted', start_type: "auto start", error_control: "normal", load_order_group: "TDI", tag_id: 0, start_name: 'NT AUTHORITY\\LocalService', dependencies: %w{NetBT Afd}, description: "Provides support for the NetBIOS over TCP/IP (NetBT) service and NetBIOS name resolution for clients on the network, therefore enabling users to share files, print, and log on to the network. If this service is stopped, these functions might be unavailable. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 780, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 100 }, 2 => { action_type: "restart", delay: 100 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "MpsSvc", display_name: "Windows Firewall", service_type: "share process", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalServiceNoNetwork', start_type: "auto start", error_control: "normal", load_order_group: "NetworkProvider", tag_id: 0, start_name: 'NT Authority\\LocalService', dependencies: %w{mpsdrv bfe}, description: "Windows Firewall helps protect your computer by preventing unauthorized users from gaining access to your computer through the Internet or a network.", interactive: false, pid: 340, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 120000 }, 2 => { action_type: "restart", delay: 300000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "mrxsmb", display_name: "SMB MiniRedirector Wrapper and Engine", service_type: "file system driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'system32\\DRIVERS\\mrxsmb.sys', start_type: "demand start", error_control: "normal", load_order_group: "Network", tag_id: 5, start_name: "", dependencies: ["rdbss"], description: "Implements the framework for the SMB filesystem redirector", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "Ntfs", display_name: "Ntfs", service_type: "file system driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: "", start_type: "demand start", error_control: "normal", load_order_group: "Boot File System", tag_id: 0, start_name: "", dependencies: [], description: "", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "Tcpip", display_name: "TCP/IP Protocol Driver", service_type: "kernel driver", current_state: "running", controls_accepted: ["stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: '\\SystemRoot\\System32\\drivers\\tcpip.sys', start_type: "boot start", error_control: "normal", load_order_group: "PNP_TDI", tag_id: 3, start_name: "", dependencies: [], description: "TCP/IP Protocol Driver", interactive: false, pid: 0, service_flags: 0, reset_period: 0, reboot_message: nil, command: nil, num_actions: 0, actions: nil, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "W32Time", display_name: "Windows Time", service_type: "share process", current_state: "running", controls_accepted: ["netbind change", "param change", "shutdown", "stop", "hardware profile change", "power event"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalService', start_type: "demand start", error_control: "normal", load_order_group: "", tag_id: 0, start_name: 'NT AUTHORITY\\LocalService', dependencies: [], description: "Maintains date and time synchronization on all clients and servers in the network. If this service is stopped, date and time synchronization will be unavailable. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 844, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 60000 }, 2 => { action_type: "restart", delay: 120000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "Winmgmt", display_name: "Windows Management Instrumentation", service_type: "share process", current_state: "running", controls_accepted: ["pause continue", "shutdown", "stop"], win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k netsvcs', start_type: "auto start", error_control: "ignore", load_order_group: "", tag_id: 0, start_name: "localSystem", dependencies: ["RPCSS"], description: "Provides a common interface and object model to access management information about operating system, devices, applications and services. If this service is stopped, most Windows-based software will not function properly. If this service is disabled, any services that explicitly depend on it will fail to start.", interactive: false, pid: 812, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 120000 }, 2 => { action_type: "restart", delay: 300000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ double("Struct::ServiceInfo", service_name: "WinRM", display_name: "Windows Remote Management (WS-Management)", service_type: "share process", current_state: "running", controls_accepted: %w{shutdown stop}, win32_exit_code: 0, service_specific_exit_code: 0, check_point: 0, wait_hint: 0, binary_path_name: 'C:\\Windows\\System32\\svchost.exe -k NetworkService', start_type: "auto start", error_control: "normal", load_order_group: "", tag_id: 0, start_name: 'NT AUTHORITY\\NetworkService', dependencies: %w{RPCSS HTTP}, description: "Windows Remote Management (WinRM) service implements the WS-Management protocol for remote management. WS-Management is a standard web services protocol used for remote software and hardware management. The WinRM service listens on the network for WS-Management requests and processes them. The WinRM Service needs to be configured with a listener using winrm.cmd command line tool or through Group Policy in order for it to listen over the network. The WinRM service provides access to WMI data and enables event collection. Event collection and subscription to events require that the service is running. WinRM messages use HTTP and HTTPS as transports. The WinRM service does not depend on IIS but is preconfigured to share a port with IIS on the same machine. The WinRM service reserves the /wsman URL prefix. To prevent conflicts with IIS, administrators should ensure that any websites hosted on IIS do not use the /wsman URL prefix.", interactive: false, pid: 932, service_flags: 0, reset_period: 86400, reboot_message: nil, command: nil, num_actions: 3, actions: { 1 => { action_type: "restart", delay: 120000 }, 2 => { action_type: "restart", delay: 300000 }, 3 => { action_type: "none", delay: 0 } }, delayed_start: 0),
+ ])
allow(Win32::Service).to receive(:exists?).and_return(true)
allow(Win32::Service).to receive(:configure).and_return(Win32::Service)
allow(Chef::ReservedNames::Win32::Security).to receive(:get_account_right).and_return([])
+ allow(Chef::ReservedNames::Win32::Security).to receive(:add_account_right).with("LocalSystem", "SeServiceLogonRight").and_return(0)
end
after(:each) do
@@ -58,40 +137,377 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "sets the current resources service name to the new resources service name" do
provider.load_current_resource
- expect(provider.current_resource.service_name).to eq("chef")
+ expect(provider.current_resource.service_name).to eq(chef_service_name)
end
it "returns the current resource" do
expect(provider.load_current_resource).to equal(provider.current_resource)
end
- it "sets the current resources status" do
- provider.load_current_resource
- expect(provider.current_resource.running).to be_truthy
- end
-
it "sets the current resources start type" do
provider.load_current_resource
expect(provider.current_resource.enabled).to be_truthy
end
- it "does not set the current resources start type if it is neither AUTO START or DISABLED" do
- allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "manual"))
- provider.load_current_resource
- expect(provider.current_resource.enabled).to be_nil
+ context "service does not exist" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(false)
+ end
+
+ %w{running enabled startup_type error_control binary_path_name
+ load_order_group dependencies run_as_user display_name }.each do |prop|
+ it "does not set #{prop}" do
+ expect(provider.current_resource.running).to be_nil
+ end
+ end
+ end
+
+ context "service exists" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(true)
+ allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
+ double("Struct::ServiceConfigInfo",
+ service_type: "share process",
+ start_type: "demand start",
+ error_control: "normal",
+ binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalServiceNetworkRestricted',
+ load_order_group: "TDI",
+ tag_id: 0,
+ dependencies: %w{NSI Tdx Afd},
+ service_start_name: 'NT Authority\\LocalService',
+ display_name: "DHCP Client"
+ ))
+ end
+
+ context "startup_type is neither :automatic or :disabled" do
+ before do
+ allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
+ double("Struct::ServiceConfigInfo",
+ service_type: "share process",
+ start_type: "demand start",
+ error_control: "normal",
+ binary_path_name: 'C:\\Windows\\system32\\svchost.exe -k LocalServiceNetworkRestricted',
+ load_order_group: "TDI",
+ tag_id: 0,
+ dependencies: %w{NSI Tdx Afd},
+ service_start_name: 'NT Authority\\LocalService',
+ display_name: "DHCP Client"
+ ))
+ end
+
+ it "does not set the current resources enabled" do
+ provider.load_current_resource
+ expect(provider.current_resource.enabled).to be_nil
+ end
+ end
+
+ it "sets the current resources running to true if it's running" do
+ allow(provider).to receive(:current_state).and_return("running")
+ provider.load_current_resource
+ expect(provider.current_resource.running).to be true
+ end
+
+ it "sets the current resources running to false if it's in any other state" do
+ allow(provider).to receive(:current_state).and_return("other state")
+ provider.load_current_resource
+ expect(provider.current_resource.running).to be false
+ end
+
+ it "sets startup_type" do
+ expect(provider.current_resource.startup_type).to be_truthy
+ end
+
+ it "sets error_control" do
+ provider.load_current_resource
+ expect(provider.current_resource.error_control).to be_truthy
+ end
+
+ it "sets binary_path_name" do
+ provider.load_current_resource
+ expect(provider.current_resource.binary_path_name).to be_truthy
+ end
+
+ it "sets load_order_group" do
+ provider.load_current_resource
+ expect(provider.current_resource.load_order_group).to be_truthy
+ end
+
+ it "sets dependencies" do
+ provider.load_current_resource
+ expect(provider.current_resource.dependencies).to be_truthy
+ end
+
+ it "sets run_as_user" do
+ provider.load_current_resource
+ expect(provider.current_resource.run_as_user).to be_truthy
+ end
+
+ it "sets display_name" do
+ provider.load_current_resource
+ expect(provider.current_resource.display_name).to be_truthy
+ end
+
+ it "sets delayed start to true if delayed start is enabled" do
+ allow(chef_service_info).to receive(:delayed_start).and_return(1)
+ provider.load_current_resource
+ expect(provider.current_resource.delayed_start).to be true
+ end
+
+ it "sets delayed start to false if delayed start is disabled" do
+ allow(chef_service_info).to receive(:delayed_start).and_return(0)
+ provider.load_current_resource
+ expect(provider.current_resource.delayed_start).to be false
+ end
+ end
+
+ describe Chef::Provider::Service::Windows, "action_create" do
+ before do
+ provider.new_resource.binary_path_name = chef_service_binary_path_name
+ end
+
+ context "service exists" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(true)
+ end
+
+ it "logs debug message" do
+ expect(logger).to receive(:trace).with("windows_service[#{chef_service_name}] already exists - nothing to do")
+ provider.action_create
+ end
+
+ it "does not converge" do
+ provider.action_create
+ expect(provider.resource_updated?).to be false
+ end
+
+ it "does not create service" do
+ expect(Win32::Service).to_not receive(:new)
+ provider.action_create
+ end
+
+ it "does not call converge_delayed_start" do
+ expect(provider).to_not receive(:converge_delayed_start)
+ provider.action_create
+ end
+ end
+
+ context "service does not exist" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(false)
+ allow(Win32::Service).to receive(:new).with(anything).and_return(true)
+ end
+
+ it "converges resource" do
+ provider.action_create
+ expect(provider.resource_updated?).to be true
+ end
+
+ it "creates service" do
+ expect(Win32::Service).to receive(:new)
+ provider.action_create
+ end
+
+ it "creates service with correct configuration" do
+ expect(Win32::Service).to receive(:new).with(
+ service_name: chef_service_name,
+ service_type: 16,
+ start_type: 2,
+ error_control: 1,
+ binary_path_name: chef_service_binary_path_name,
+ service_start_name: "LocalSystem",
+ desired_access: 983551
+ )
+ provider.action_create
+ end
+
+ it "calls converge_delayed_start" do
+ expect(provider).to receive(:converge_delayed_start)
+ provider.action_create
+ end
+ end
+ end
+
+ describe Chef::Provider::Service::Windows, "action_delete" do
+ context "service exists" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(true)
+ allow(Win32::Service).to receive(:delete).with(chef_service_name).and_return(true)
+ end
+
+ it "converges resource" do
+ provider.action_delete
+ expect(provider.resource_updated?).to be true
+ end
+
+ it "deletes service" do
+ expect(Win32::Service).to receive(:delete).with(chef_service_name)
+ provider.action_delete
+ end
+ end
+
+ context "service does not exist" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(false)
+ end
+
+ it "logs debug message" do
+ expect(logger).to receive(:trace).with("windows_service[#{chef_service_name}] does not exist - nothing to do")
+ provider.action_delete
+ end
+
+ it "does not converge" do
+ provider.action_delete
+ expect(provider.resource_updated?).to be false
+ end
+
+ it "does not delete service" do
+ expect(Win32::Service).to_not receive(:delete)
+ provider.action_delete
+ end
+ end
+ end
+
+ describe Chef::Provider::Service::Windows, "action_configure" do
+ context "service exists" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(true)
+ allow(Win32::Service).to receive(:configure).with(anything).and_return(true)
+ end
+
+ it "works around #6300 if run_as_user is default" do
+ new_resource.run_as_user = new_resource.class.properties[:run_as_user].default
+ expect(provider.new_resource).to receive(:run_as_user=)
+ .with(new_resource.class.properties[:run_as_user].default)
+ provider.action_configure
+ end
+
+ # Attributes that are Strings
+ %i{binary_path_name load_order_group dependencies run_as_user
+ display_name description}.each do |attr|
+ it "configures service if #{attr} has changed" do
+ provider.current_resource.send("#{attr}=", "old value")
+ provider.new_resource.send("#{attr}=", "new value")
+
+ expect(Win32::Service).to receive(:configure)
+ provider.action_configure
+ end
+ end
+
+ # Attributes that are Integers
+ %i{service_type error_control}.each do |attr|
+ it "configures service if #{attr} has changed" do
+ provider.current_resource.send("#{attr}=", 1)
+ provider.new_resource.send("#{attr}=", 2)
+
+ expect(Win32::Service).to receive(:configure)
+ provider.action_configure
+ end
+ end
+
+ it "configures service if startup_type has changed" do
+ provider.current_resource.startup_type = :automatic
+ provider.new_resource.startup_type = :manual
+
+ expect(Win32::Service).to receive(:configure)
+ provider.action_configure
+ end
+
+ it "calls converge_delayed_start" do
+ expect(provider).to receive(:converge_delayed_start)
+ provider.action_configure
+ end
+ end
+
+ context "service does not exist" do
+ before do
+ allow(Win32::Service).to receive(:exists?).with(chef_service_name).and_return(false)
+ end
+
+ it "logs warning" do
+ expect(logger).to receive(:warn)
+ .with("windows_service[#{chef_service_name}] does not exist. Maybe you need to prepend action :create")
+ provider.action_configure
+ end
+
+ it "does not converge" do
+ provider.action_configure
+ expect(provider.resource_updated?).to be false
+ end
+
+ it "does not convigure service" do
+ expect(Win32::Service).to_not receive(:configure)
+ provider.action_configure
+ end
+
+ it "does not call converge_delayed_start" do
+ expect(provider).to_not receive(:converge_delayed_start)
+ provider.action_configure
+ end
+ end
+ end
+
+ describe Chef::Provider::Service::Windows, "converge_delayed_start" do
+ before do
+ allow(Win32::Service).to receive(:configure).and_return(true)
+ end
+
+ it "works around #6300 if delayed_start is default" do
+ new_resource.delayed_start = new_resource.class.properties[:delayed_start].default
+ expect(provider.new_resource).to receive(:delayed_start=)
+ .with(new_resource.class.properties[:delayed_start].default)
+ provider.send(:converge_delayed_start)
+ end
+
+ context "delayed start needs to be updated" do
+ before do
+ provider.current_resource.delayed_start = false
+ provider.new_resource.delayed_start = true
+ end
+
+ it "configures delayed start" do
+ expect(Win32::Service).to receive(:configure)
+ provider.send(:converge_delayed_start)
+ end
+
+ it "configures delayed start with correct params" do
+ expect(Win32::Service).to receive(:configure).with(service_name: chef_service_name, delayed_start: 1)
+ provider.send(:converge_delayed_start)
+ end
+
+ it "converges resource" do
+ provider.send(:converge_delayed_start)
+ expect(provider.resource_updated?).to be true
+ end
+ end
+
+ context "delayed start does not need to be updated" do
+ before do
+ provider.current_resource.delayed_start = false
+ provider.new_resource.delayed_start = false
+ end
+
+ it "does not configure delayed start" do
+ expect(Win32::Service).to_not receive(:configure)
+ provider.send(:converge_delayed_start)
+ end
+
+ it "does not converge" do
+ provider.send(:converge_delayed_start)
+ expect(provider.resource_updated?).to be false
+ end
+ end
end
describe Chef::Provider::Service::Windows, "start_service" do
before(:each) do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "stopped"),
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "stopped"),
+ double("StatusStruct", current_state: "running"))
end
it "calls the start command if one is specified" do
- new_resource.start_command "sc start chef"
- expect(provider).to receive(:shell_out!).with("#{new_resource.start_command}").and_return("Starting custom service")
+ new_resource.start_command "sc start #{chef_service_name}"
+ expect(provider).to receive(:shell_out!).with((new_resource.start_command).to_s).and_return("Starting custom service")
provider.start_service
expect(new_resource.updated_by_last_action?).to be_truthy
end
@@ -111,7 +527,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "does nothing if the service is running" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "running"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
provider.start_service
@@ -120,7 +536,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "raises an error if the service is paused" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "paused"))
+ double("StatusStruct", current_state: "paused"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
expect { provider.start_service }.to raise_error( Chef::Exceptions::Service )
@@ -129,9 +545,9 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "waits and continues if the service is in start_pending" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "start pending"),
- double("StatusStruct", :current_state => "start pending"),
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "start pending"),
+ double("StatusStruct", current_state: "start pending"),
+ double("StatusStruct", current_state: "running"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
provider.start_service
@@ -140,7 +556,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "fails if the service is in stop_pending" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "stop pending"))
+ double("StatusStruct", current_state: "stop pending"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
expect { provider.start_service }.to raise_error( Chef::Exceptions::Service )
@@ -148,19 +564,11 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
end
describe "running as a different account" do
- let(:old_run_as_user) { new_resource.run_as_user }
- let(:old_run_as_password) { new_resource.run_as_password }
-
before do
new_resource.run_as_user(".\\wallace")
new_resource.run_as_password("Wensleydale")
end
- after do
- new_resource.run_as_user(old_run_as_user)
- new_resource.run_as_password(old_run_as_password)
- end
-
it "calls #grant_service_logon if the :run_as_user and :run_as_password attributes are present" do
expect(Win32::Service).to receive(:start)
expect(provider).to receive(:grant_service_logon).and_return(true)
@@ -173,6 +581,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
expect(Chef::ReservedNames::Win32::Security).not_to receive(:add_account_right).with("wallace", service_right)
provider.start_service
end
+
+ it "skips the rights check for LocalSystem" do
+ new_resource.run_as_user("LocalSystem")
+ expect(Win32::Service).to receive(:start)
+ expect(Chef::ReservedNames::Win32::Security).not_to receive(:get_account_right)
+ expect(Chef::ReservedNames::Win32::Security).not_to receive(:add_account_right)
+ provider.start_service
+ end
end
end
@@ -180,13 +596,13 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
before(:each) do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "running"),
- double("StatusStruct", :current_state => "stopped"))
+ double("StatusStruct", current_state: "running"),
+ double("StatusStruct", current_state: "stopped"))
end
it "calls the stop command if one is specified" do
- new_resource.stop_command "sc stop chef"
- expect(provider).to receive(:shell_out!).with("#{new_resource.stop_command}").and_return("Stopping custom service")
+ new_resource.stop_command "sc stop #{chef_service_name}"
+ expect(provider).to receive(:shell_out!).with((new_resource.stop_command).to_s).and_return("Stopping custom service")
provider.stop_service
expect(new_resource.updated_by_last_action?).to be_truthy
end
@@ -206,7 +622,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "does nothing if the service is stopped" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "stopped"))
+ double("StatusStruct", current_state: "stopped"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
provider.stop_service
@@ -215,7 +631,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "raises an error if the service is paused" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "paused"))
+ double("StatusStruct", current_state: "paused"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:start).with(new_resource.service_name)
expect { provider.stop_service }.to raise_error( Chef::Exceptions::Service )
@@ -224,9 +640,9 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "waits and continue if the service is in stop_pending" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "stop pending"),
- double("StatusStruct", :current_state => "stop pending"),
- double("StatusStruct", :current_state => "stopped"))
+ double("StatusStruct", current_state: "stop pending"),
+ double("StatusStruct", current_state: "stop pending"),
+ double("StatusStruct", current_state: "stopped"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
provider.stop_service
@@ -235,7 +651,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "fails if the service is in start_pending" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "start pending"))
+ double("StatusStruct", current_state: "start pending"))
provider.load_current_resource
expect(Win32::Service).not_to receive(:stop).with(new_resource.service_name)
expect { provider.stop_service }.to raise_error( Chef::Exceptions::Service )
@@ -244,7 +660,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "passes custom timeout to the stop command if provided" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "running"))
new_resource.timeout 1
expect(Win32::Service).to receive(:stop).with(new_resource.service_name)
Timeout.timeout(2) do
@@ -259,17 +675,17 @@ describe Chef::Provider::Service::Windows, "load_current_resource" 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}")
+ expect(provider).to receive(:shell_out!).with((new_resource.restart_command).to_s)
provider.restart_service
expect(new_resource.updated_by_last_action?).to be_truthy
end
it "stops then starts the service if it is running" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "running"),
- double("StatusStruct", :current_state => "stopped"),
- double("StatusStruct", :current_state => "stopped"),
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "running"),
+ double("StatusStruct", current_state: "stopped"),
+ double("StatusStruct", current_state: "stopped"),
+ double("StatusStruct", current_state: "running"))
expect(Win32::Service).to receive(:stop).with(new_resource.service_name)
expect(Win32::Service).to receive(:start).with(new_resource.service_name)
provider.restart_service
@@ -278,9 +694,9 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
it "just starts the service if it is stopped" do
allow(Win32::Service).to receive(:status).with(new_resource.service_name).and_return(
- double("StatusStruct", :current_state => "stopped"),
- double("StatusStruct", :current_state => "stopped"),
- double("StatusStruct", :current_state => "running"))
+ double("StatusStruct", current_state: "stopped"),
+ double("StatusStruct", current_state: "stopped"),
+ double("StatusStruct", current_state: "running"))
expect(Win32::Service).to receive(:start).with(new_resource.service_name)
provider.restart_service
expect(new_resource.updated_by_last_action?).to be_truthy
@@ -299,11 +715,11 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
describe Chef::Provider::Service::Windows, "enable_service" do
before(:each) do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "disabled"))
+ double("ConfigStruct", start_type: "disabled"))
end
it "enables service" do
- expect(Win32::Service).to receive(:configure).with(:service_name => new_resource.service_name, :start_type => Win32::Service::AUTO_START)
+ expect(Win32::Service).to receive(:configure).with(service_name: new_resource.service_name, start_type: Win32::Service::AUTO_START)
provider.enable_service
expect(new_resource.updated_by_last_action?).to be_truthy
end
@@ -319,14 +735,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
describe Chef::Provider::Service::Windows, "action_enable" do
it "does nothing if the service is enabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "auto start"))
+ double("ConfigStruct", start_type: "auto start"))
expect(provider).not_to receive(:enable_service)
provider.action_enable
end
it "enables the service if it is not set to automatic start" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "disabled"))
+ double("ConfigStruct", start_type: "disabled"))
expect(provider).to receive(:enable_service)
provider.action_enable
end
@@ -335,14 +751,14 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
describe Chef::Provider::Service::Windows, "action_disable" do
it "does nothing if the service is disabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "disabled"))
+ double("ConfigStruct", start_type: "disabled"))
expect(provider).not_to receive(:disable_service)
provider.action_disable
end
it "disables the service if it is not set to disabled" do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "auto start"))
+ double("ConfigStruct", start_type: "auto start"))
expect(provider).to receive(:disable_service)
provider.action_disable
end
@@ -351,7 +767,7 @@ describe Chef::Provider::Service::Windows, "load_current_resource" do
describe Chef::Provider::Service::Windows, "disable_service" do
before(:each) do
allow(Win32::Service).to receive(:config_info).with(new_resource.service_name).and_return(
- double("ConfigStruct", :start_type => "auto start"))
+ double("ConfigStruct", start_type: "auto start"))
end
it "disables service" do
@@ -369,36 +785,41 @@ 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|
+ %i{automatic manual disabled}.each do |type|
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")
+ allow(provider).to receive(:current_startup_type).and_return(:fire)
expect(provider).to receive(:set_startup_type).with(type)
provider.action_configure_startup
end
it "leaves the startup type as #{type} if it is already set" do
new_resource.startup_type(type)
- allow(provider).to receive(:current_start_type).and_return(win32)
+ allow(provider).to receive(:current_startup_type).and_return(type)
expect(provider).not_to receive(:set_startup_type).with(type)
provider.action_configure_startup
end
end
+
+ it "calls converge_delayed_start" do
+ expect(provider).to receive(:converge_delayed_start)
+ provider.action_configure_startup
+ end
end
describe Chef::Provider::Service::Windows, "set_start_type" do
it "when called with :automatic it calls Win32::Service#configure with Win32::Service::AUTO_START" do
- expect(Win32::Service).to receive(:configure).with(:service_name => new_resource.service_name, :start_type => Win32::Service::AUTO_START)
+ expect(Win32::Service).to receive(:configure).with(service_name: new_resource.service_name, start_type: Win32::Service::AUTO_START)
provider.send(:set_startup_type, :automatic)
end
it "when called with :manual it calls Win32::Service#configure with Win32::Service::DEMAND_START" do
- expect(Win32::Service).to receive(:configure).with(:service_name => new_resource.service_name, :start_type => Win32::Service::DEMAND_START)
+ expect(Win32::Service).to receive(:configure).with(service_name: new_resource.service_name, start_type: Win32::Service::DEMAND_START)
provider.send(:set_startup_type, :manual)
end
it "when called with :disabled it calls Win32::Service#configure with Win32::Service::DISABLED" do
- expect(Win32::Service).to receive(:configure).with(:service_name => new_resource.service_name, :start_type => Win32::Service::DISABLED)
+ expect(Win32::Service).to receive(:configure).with(service_name: new_resource.service_name, start_type: Win32::Service::DISABLED)
provider.send(:set_startup_type, :disabled)
end
diff --git a/spec/unit/provider/service_spec.rb b/spec/unit/provider/service_spec.rb
index c788cb223e..f3e725abb6 100644
--- a/spec/unit/provider/service_spec.rb
+++ b/spec/unit/provider/service_spec.rb
@@ -99,7 +99,7 @@ describe Chef::Provider::Service do
describe "action_restart" do
before do
- @current_resource.supports(:restart => true)
+ @current_resource.supports(restart: true)
end
it "should restart the service if it's supported and set the resource as updated" do
@@ -118,11 +118,11 @@ describe Chef::Provider::Service do
describe "action_reload" do
before do
- @new_resource.supports(:reload => true)
+ @new_resource.supports(reload: true)
end
it "should raise an exception if reload isn't supported" do
- @new_resource.supports(:reload => false)
+ @new_resource.supports(reload: false)
@new_resource.reload_command(false)
expect { @provider.run_action(:reload) }.to raise_error(Chef::Exceptions::UnsupportedAction)
end
diff --git a/spec/unit/provider/subversion_spec.rb b/spec/unit/provider/subversion_spec.rb
index 55d6dc5d24..5233ecb229 100644
--- a/spec/unit/provider/subversion_spec.rb
+++ b/spec/unit/provider/subversion_spec.rb
@@ -46,7 +46,7 @@ describe Chef::Provider::Subversion do
it "converts resource attributes to options for shell_out" 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
@@ -73,18 +73,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] }]
- expect(@provider).to receive(:shell_out!).with(*expected_command).
- and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => ""))
+ 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: ""))
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] }]
- expect(@provider).to receive(:shell_out!).with(*expected_command).
- and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => ""))
+ 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: ""))
expect(@provider.find_current_revision).to be_nil
end
@@ -128,18 +128,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"
@resource.revision "HEAD"
- 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 => ""))
+ 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 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] }]
- expect(@provider).to receive(:shell_out!).with(*expected_command).
- and_return(double("ShellOut result", :stdout => example_svn_info, :stderr => ""))
+ 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")
end
diff --git a/spec/unit/provider/systemd_unit_spec.rb b/spec/unit/provider/systemd_unit_spec.rb
index 6909c9d86b..00f39d0fd9 100644
--- a/spec/unit/provider/systemd_unit_spec.rb
+++ b/spec/unit/provider/systemd_unit_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Nathan Williams (<nath.e.will@gmail.com>)
-# Copyright:: Copyright (c), Nathan Williams
+# Copyright:: Copyright 2016-2018, Nathan Williams
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,21 +19,11 @@
require "spec_helper"
describe Chef::Provider::SystemdUnit do
- let(:node) do
- Chef::Node.new.tap do |n|
- n.default["etc"] = {}
- n.default["etc"]["passwd"] = {
- "joe" => {
- "uid" => 1_000,
- },
- }
- end
- end
+ let(:node) { Chef::Node.new }
let(:events) { Chef::EventDispatch::Dispatcher.new }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
let(:unit_name) { "sysstat-collect\\x2d.timer" }
- let(:unit_name_escaped) { "sysstat-collect\\\\x2d.timer" }
let(:user_name) { "joe" }
let(:current_resource) { Chef::Resource::SystemdUnit.new(unit_name) }
let(:new_resource) { Chef::Resource::SystemdUnit.new(unit_name) }
@@ -59,30 +49,31 @@ describe Chef::Provider::SystemdUnit do
let(:user_cmd_opts) do
{
- :user => "joe",
- :environment => {
+ user: "joe",
+ environment: {
"DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/1000/bus",
},
}
end
let(:shell_out_success) do
- double("shell_out_with_systems_locale", :exitstatus => 0, :error? => false)
+ double("shell_out", exitstatus: 0, error?: false)
end
let(:shell_out_failure) do
- double("shell_out_with_systems_locale", :exitstatus => 1, :error? => true)
+ double("shell_out", exitstatus: 1, error?: true)
end
let(:shell_out_masked) do
- double("shell_out_with_systems_locale", :exit_status => 0, :error? => false, :stdout => "masked")
+ double("shell_out", exit_status: 0, error?: false, stdout: "masked")
end
let(:shell_out_static) do
- double("shell_out_with_systems_locale", :exit_status => 0, :error? => false, :stdout => "static")
+ double("shell_out", exit_status: 0, error?: false, stdout: "static")
end
before(:each) do
+ allow(Etc).to receive(:getpwnam).and_return(OpenStruct.new(uid: 1000))
allow(Chef::Resource::SystemdUnit).to receive(:new)
.with(unit_name)
.and_return(current_resource)
@@ -258,7 +249,7 @@ describe Chef::Provider::SystemdUnit do
.and_return(systemctl_path)
end
- describe "creates/deletes the unit" do
+ describe "creates/deletes/presets/reverts the unit" do
it "creates the unit file when it does not exist" do
allow(provider).to receive(:manage_unit_file)
.with(:create)
@@ -288,49 +279,53 @@ describe Chef::Provider::SystemdUnit do
provider.action_create
end
- it "triggers a daemon-reload when creating a unit with triggers_reload" do
- allow(provider).to receive(:manage_unit_file).with(:create)
- expect(new_resource.triggers_reload).to eq true
- allow(provider).to receive(:shell_out_with_systems_locale!)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} daemon-reload")
- provider.action_create
- end
+ context "when a user is specified" do
+ it "triggers a daemon-reload when creating a unit with triggers_reload" do
+ new_resource.user("joe")
+ allow(provider).to receive(:manage_unit_file).with(:create)
+ expect(new_resource.triggers_reload).to eq true
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ provider.action_create
+ end
- it "triggers a daemon-reload when deleting a unit with triggers_reload" do
- allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
- allow(provider).to receive(:manage_unit_file).with(:delete)
- expect(new_resource.triggers_reload).to eq true
- allow(provider).to receive(:shell_out_with_systems_locale!)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} daemon-reload")
- provider.action_delete
- end
+ it "triggers a daemon-reload when deleting a unit with triggers_reload" do
+ new_resource.user("joe")
+ allow(File).to receive(:exist?)
+ .with(unit_path_user)
+ .and_return(true)
+ allow(provider).to receive(:manage_unit_file).with(:delete)
+ expect(new_resource.triggers_reload).to eq true
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ provider.action_delete
+ end
- it "does not trigger a daemon-reload when creating a unit without triggers_reload" do
- new_resource.triggers_reload(false)
- allow(provider).to receive(:manage_unit_file).with(:create)
- allow(provider).to receive(:shell_out_with_systems_locale!)
- expect(provider).to_not receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} daemon-reload")
- provider.action_create
- end
+ it "does not trigger a daemon-reload when creating a unit without triggers_reload" do
+ new_resource.user("joe")
+ new_resource.triggers_reload(false)
+ allow(provider).to receive(:manage_unit_file).with(:create)
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to_not receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ provider.action_create
+ end
- it "does not trigger a daemon-reload when deleting a unit without triggers_reload" do
- new_resource.triggers_reload(false)
- allow(File).to receive(:exist?)
- .with(unit_path_system)
- .and_return(true)
- allow(provider).to receive(:manage_unit_file).with(:delete)
- allow(provider).to receive(:shell_out_with_systems_locale!)
- expect(provider).to_not receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} daemon-reload")
- provider.action_delete
- end
+ it "does not trigger a daemon-reload when deleting a unit without triggers_reload" do
+ new_resource.user("joe")
+ new_resource.triggers_reload(false)
+ allow(File).to receive(:exist?)
+ .with(unit_path_user)
+ .and_return(true)
+ allow(provider).to receive(:manage_unit_file).with(:delete)
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to_not receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "daemon-reload", **user_cmd_opts, default_env: false)
+ provider.action_delete
+ end
- context "when a user is specified" do
it "deletes the file when it exists" do
new_resource.user("joe")
allow(File).to receive(:exist?)
@@ -353,9 +348,66 @@ describe Chef::Provider::SystemdUnit do
expect(provider).to_not receive(:manage_unit_file)
provider.action_delete
end
+
+ it "presets the unit" do
+ new_resource.user("joe")
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "preset", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
+ provider.action_preset
+ end
+
+ it "reverts the unit" do
+ new_resource.user("joe")
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "revert", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
+ provider.action_revert
+ end
end
context "when no user is specified" do
+ it "triggers a daemon-reload when creating a unit with triggers_reload" do
+ allow(provider).to receive(:manage_unit_file).with(:create)
+ expect(new_resource.triggers_reload).to eq true
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ provider.action_create
+ end
+
+ it "triggers a daemon-reload when deleting a unit with triggers_reload" do
+ allow(File).to receive(:exist?)
+ .with(unit_path_system)
+ .and_return(true)
+ allow(provider).to receive(:manage_unit_file).with(:delete)
+ expect(new_resource.triggers_reload).to eq true
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ provider.action_delete
+ end
+
+ it "does not trigger a daemon-reload when creating a unit without triggers_reload" do
+ new_resource.triggers_reload(false)
+ allow(provider).to receive(:manage_unit_file).with(:create)
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to_not receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ provider.action_create
+ end
+
+ it "does not trigger a daemon-reload when deleting a unit without triggers_reload" do
+ new_resource.triggers_reload(false)
+ allow(File).to receive(:exist?)
+ .with(unit_path_system)
+ .and_return(true)
+ allow(provider).to receive(:manage_unit_file).with(:delete)
+ allow(provider).to receive(:shell_out_compacted!)
+ expect(provider).to_not receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "daemon-reload", default_env: false)
+ provider.action_delete
+ end
it "deletes the file when it exists" do
allow(File).to receive(:exist?)
.with(unit_path_system)
@@ -376,16 +428,38 @@ describe Chef::Provider::SystemdUnit do
expect(provider).to_not receive(:manage_unit_file)
provider.action_delete
end
+
+ it "presets the unit" do
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "preset", unit_name)
+ .and_return(shell_out_success)
+ provider.action_preset
+ end
+
+ it "reverts the unit" do
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "revert", unit_name)
+ .and_return(shell_out_success)
+ provider.action_revert
+ end
end
end
- describe "enables/disables the unit" do
+ describe "enables/disables/reenables the unit" do
context "when a user is specified" do
+ it "reenables the unit" do
+ current_resource.user(user_name)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "reenable", unit_name, **user_cmd_opts)
+ .and_return(shell_out_success)
+ provider.action_reenable
+ end
+
it "enables the unit when it is disabled" do
current_resource.user(user_name)
current_resource.enabled(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user enable #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "enable", unit_name, **user_cmd_opts)
.and_return(shell_out_success)
provider.action_enable
end
@@ -393,22 +467,22 @@ describe Chef::Provider::SystemdUnit do
it "does not enable the unit when it is enabled" do
current_resource.user(user_name)
current_resource.enabled(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_enable
end
it "does not enable the unit when it is static" do
current_resource.user(user_name)
current_resource.static(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_enable
end
it "disables the unit when it is enabled" do
current_resource.user(user_name)
current_resource.enabled(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user disable #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "disable", unit_name, **user_cmd_opts)
.and_return(shell_out_success)
provider.action_disable
end
@@ -416,57 +490,64 @@ describe Chef::Provider::SystemdUnit do
it "does not disable the unit when it is disabled" do
current_resource.user(user_name)
current_resource.enabled(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_disable
end
it "does not disable the unit when it is static" do
current_resource.user(user_name)
current_resource.static(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_disable
end
end
context "when no user is specified" do
+ it "reenables the unit" do
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "reenable", unit_name)
+ .and_return(shell_out_success)
+ provider.action_reenable
+ end
+
it "enables the unit when it is disabled" do
current_resource.enabled(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system enable #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "enable", unit_name)
.and_return(shell_out_success)
provider.action_enable
end
it "does not enable the unit when it is enabled" do
current_resource.enabled(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_enable
end
it "does not enable the unit when it is static" do
current_resource.static(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_enable
end
it "disables the unit when it is enabled" do
current_resource.enabled(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system disable #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "disable", unit_name)
.and_return(shell_out_success)
provider.action_disable
end
it "does not disable the unit when it is disabled" do
current_resource.enabled(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_disable
end
it "does not disable the unit when it is static" do
current_resource.user(user_name)
current_resource.static(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_disable
end
end
@@ -477,8 +558,8 @@ describe Chef::Provider::SystemdUnit do
it "masks the unit when it is unmasked" do
current_resource.user(user_name)
current_resource.masked(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user mask #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "mask", unit_name, **user_cmd_opts)
.and_return(shell_out_success)
provider.action_mask
end
@@ -486,15 +567,15 @@ describe Chef::Provider::SystemdUnit do
it "does not mask the unit when it is masked" do
current_resource.user(user_name)
current_resource.masked(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_mask
end
it "unmasks the unit when it is masked" do
current_resource.user(user_name)
current_resource.masked(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user unmask #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "unmask", unit_name, **user_cmd_opts)
.and_return(shell_out_success)
provider.action_unmask
end
@@ -502,7 +583,7 @@ describe Chef::Provider::SystemdUnit do
it "does not unmask the unit when it is unmasked" do
current_resource.user(user_name)
current_resource.masked(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_unmask
end
end
@@ -510,29 +591,29 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "masks the unit when it is unmasked" do
current_resource.masked(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system mask #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "mask", unit_name)
.and_return(shell_out_success)
provider.action_mask
end
it "does not mask the unit when it is masked" do
current_resource.masked(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_mask
end
it "unmasks the unit when it is masked" do
current_resource.masked(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system unmask #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "unmask", unit_name)
.and_return(shell_out_success)
provider.action_unmask
end
it "does not unmask the unit when it is unmasked" do
current_resource.masked(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_unmask
end
end
@@ -543,8 +624,8 @@ describe Chef::Provider::SystemdUnit do
it "starts the unit when it is inactive" do
current_resource.user(user_name)
current_resource.active(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user start #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "start", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_start
end
@@ -552,15 +633,15 @@ describe Chef::Provider::SystemdUnit do
it "does not start the unit when it is active" do
current_resource.user(user_name)
current_resource.active(true)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_start
end
it "stops the unit when it is active" do
current_resource.user(user_name)
current_resource.active(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user stop #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "stop", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_stop
end
@@ -568,7 +649,7 @@ describe Chef::Provider::SystemdUnit do
it "does not stop the unit when it is inactive" do
current_resource.user(user_name)
current_resource.active(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_stop
end
end
@@ -576,29 +657,29 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "starts the unit when it is inactive" do
current_resource.active(false)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system start #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "start", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_start
end
it "does not start the unit when it is active" do
current_resource.active(true)
- expect(provider).to_not receive(:shell_out_with_systems_locale!)
+ expect(provider).to_not receive(:shell_out_compacted!)
provider.action_start
end
it "stops the unit when it is active" do
current_resource.active(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system stop #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "stop", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_stop
end
it "does not stop the unit when it is inactive" do
current_resource.active(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_stop
end
end
@@ -608,8 +689,8 @@ describe Chef::Provider::SystemdUnit do
context "when a user is specified" do
it "restarts the unit" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user restart #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "restart", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_restart
end
@@ -617,8 +698,8 @@ describe Chef::Provider::SystemdUnit do
it "reloads the unit if active" do
current_resource.user(user_name)
current_resource.active(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user reload #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "reload", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_reload
end
@@ -626,30 +707,30 @@ describe Chef::Provider::SystemdUnit do
it "does not reload if the unit is inactive" do
current_resource.user(user_name)
current_resource.active(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_reload
end
end
context "when no user is specified" do
it "restarts the unit" do
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system restart #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "restart", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_restart
end
it "reloads the unit if active" do
current_resource.active(true)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system reload #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "reload", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_reload
end
it "does not reload the unit if inactive" do
current_resource.active(false)
- expect(provider).not_to receive(:shell_out_with_systems_locale!)
+ expect(provider).not_to receive(:shell_out_compacted!)
provider.action_reload
end
end
@@ -659,8 +740,8 @@ describe Chef::Provider::SystemdUnit do
context "when a user is specified" do
it "try-restarts the unit" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user try-restart #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "try-restart", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_try_restart
end
@@ -668,8 +749,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "try-restarts the unit" do
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system try-restart #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "try-restart", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_try_restart
end
@@ -680,8 +761,8 @@ describe Chef::Provider::SystemdUnit do
context "when a user is specified" do
it "reload-or-restarts the unit" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user reload-or-restart #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "reload-or-restart", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_reload_or_restart
end
@@ -689,8 +770,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "reload-or-restarts the unit" do
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system reload-or-restart #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "reload-or-restart", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_reload_or_restart
end
@@ -701,8 +782,8 @@ describe Chef::Provider::SystemdUnit do
context "when a user is specified" do
it "reload-or-try-restarts the unit" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --user reload-or-try-restart #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--user", "reload-or-try-restart", unit_name, **user_cmd_opts, default_env: false)
.and_return(shell_out_success)
provider.action_reload_or_try_restart
end
@@ -710,8 +791,8 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "reload-or-try-restarts the unit" do
- expect(provider).to receive(:shell_out_with_systems_locale!)
- .with("#{systemctl_path} --system reload-or-try-restart #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted!)
+ .with(systemctl_path, "--system", "reload-or-try-restart", unit_name, default_env: false)
.and_return(shell_out_success)
provider.action_reload_or_try_restart
end
@@ -721,22 +802,22 @@ describe Chef::Provider::SystemdUnit do
describe "#active?" do
before(:each) do
provider.current_resource = current_resource
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
context "when a user is specified" do
it "returns true when unit is active" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-active #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
.and_return(shell_out_success)
expect(provider.active?).to be true
end
it "returns false when unit is inactive" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-active #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-active", unit_name, user_cmd_opts)
.and_return(shell_out_failure)
expect(provider.active?).to be false
end
@@ -744,15 +825,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when unit is active" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-active #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-active", unit_name)
.and_return(shell_out_success)
expect(provider.active?).to be true
end
it "returns false when unit is not active" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-active #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-active", unit_name)
.and_return(shell_out_failure)
expect(provider.active?).to be false
end
@@ -762,22 +843,22 @@ describe Chef::Provider::SystemdUnit do
describe "#enabled?" do
before(:each) do
provider.current_resource = current_resource
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
context "when a user is specified" do
it "returns true when unit is enabled" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-enabled #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
.and_return(shell_out_success)
expect(provider.enabled?).to be true
end
it "returns false when unit is not enabled" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-enabled #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
.and_return(shell_out_failure)
expect(provider.enabled?).to be false
end
@@ -785,15 +866,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when unit is enabled" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-enabled #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
.and_return(shell_out_success)
expect(provider.enabled?).to be true
end
it "returns false when unit is not enabled" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-enabled #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
.and_return(shell_out_failure)
expect(provider.enabled?).to be false
end
@@ -803,22 +884,22 @@ describe Chef::Provider::SystemdUnit do
describe "#masked?" do
before(:each) do
provider.current_resource = current_resource
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
context "when a user is specified" do
it "returns true when the unit is masked" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user status #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
.and_return(shell_out_masked)
expect(provider.masked?).to be true
end
it "returns false when the unit is not masked" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user status #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "status", unit_name, user_cmd_opts)
.and_return(shell_out_static)
expect(provider.masked?).to be false
end
@@ -826,15 +907,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when the unit is masked" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system status #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "status", unit_name)
.and_return(shell_out_masked)
expect(provider.masked?).to be true
end
it "returns false when the unit is not masked" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system status #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "status", unit_name)
.and_return(shell_out_static)
expect(provider.masked?).to be false
end
@@ -844,22 +925,22 @@ describe Chef::Provider::SystemdUnit do
describe "#static?" do
before(:each) do
provider.current_resource = current_resource
- allow(provider).to receive(:which).with("systemctl").and_return("#{systemctl_path}")
+ allow(provider).to receive(:which).with("systemctl").and_return(systemctl_path.to_s)
end
context "when a user is specified" do
it "returns true when the unit is static" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-enabled #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
.and_return(shell_out_static)
expect(provider.static?).to be true
end
it "returns false when the unit is not static" do
current_resource.user(user_name)
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --user is-enabled #{unit_name_escaped}", user_cmd_opts)
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--user", "is-enabled", unit_name, user_cmd_opts)
.and_return(shell_out_masked)
expect(provider.static?).to be false
end
@@ -867,15 +948,15 @@ describe Chef::Provider::SystemdUnit do
context "when no user is specified" do
it "returns true when the unit is static" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-enabled #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
.and_return(shell_out_static)
expect(provider.static?).to be true
end
it "returns false when the unit is not static" do
- expect(provider).to receive(:shell_out)
- .with("#{systemctl_path} --system is-enabled #{unit_name_escaped}", {})
+ expect(provider).to receive(:shell_out_compacted)
+ .with(systemctl_path, "--system", "is-enabled", unit_name)
.and_return(shell_out_masked)
expect(provider.static?).to be false
end
diff --git a/spec/unit/provider/template/content_spec.rb b/spec/unit/provider/template/content_spec.rb
index 8f30d8f868..67d4eba138 100644
--- a/spec/unit/provider/template/content_spec.rb
+++ b/spec/unit/provider/template/content_spec.rb
@@ -30,20 +30,20 @@ describe Chef::Provider::Template::Content do
let(:new_resource) do
double("Chef::Resource::Template (new)",
- :cookbook_name => "openldap",
- :recipe_name => "default",
- :source_line => "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
- :source_line_file => "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb",
- :source_line_number => "2",
- :source => "openldap_stuff.conf.erb",
- :name => "openldap_stuff.conf",
- :path => resource_path,
- :local => false,
- :cookbook => nil,
- :variables => {},
- :inline_helper_blocks => {},
- :inline_helper_modules => [],
- :helper_modules => [])
+ cookbook_name: "openldap",
+ recipe_name: "default",
+ source_line: "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
+ source_line_file: "/Users/lamont/solo/cookbooks/openldap/recipes/default.rb",
+ source_line_number: "2",
+ source: "openldap_stuff.conf.erb",
+ name: "openldap_stuff.conf",
+ path: resource_path,
+ local: false,
+ cookbook: nil,
+ variables: {},
+ inline_helper_blocks: {},
+ inline_helper_modules: [],
+ helper_modules: [])
end
let(:rendered_file_locations) do
@@ -58,7 +58,7 @@ describe Chef::Provider::Template::Content do
cl.load_cookbooks
cookbook_collection = Chef::CookbookCollection.new(cl)
node = Chef::Node.new
- double("Chef::Resource::RunContext", :node => node, :cookbook_collection => cookbook_collection)
+ double("Chef::Resource::RunContext", node: node, cookbook_collection: cookbook_collection)
end
let(:content) do
@@ -130,38 +130,38 @@ describe Chef::Provider::Template::Content do
describe "when using location helpers" do
let(:new_resource) do
double("Chef::Resource::Template (new)",
- :cookbook_name => "openldap",
- :recipe_name => "default",
- :source_line => CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
- :source_line_file => CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb",
- :source_line_number => "2",
- :source => "helpers.erb",
- :name => "helpers.erb",
- :path => CHEF_SPEC_DATA + "/cookbooks/openldap/templates/default/helpers.erb",
- :local => false,
- :cookbook => nil,
- :variables => {},
- :inline_helper_blocks => {},
- :inline_helper_modules => [],
- :helper_modules => [])
+ cookbook_name: "openldap",
+ recipe_name: "default",
+ source_line: CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb:2:in `from_file'",
+ source_line_file: CHEF_SPEC_DATA + "/cookbooks/openldap/recipes/default.rb",
+ source_line_number: "2",
+ source: "helpers.erb",
+ name: "helpers.erb",
+ path: CHEF_SPEC_DATA + "/cookbooks/openldap/templates/default/helpers.erb",
+ local: false,
+ cookbook: nil,
+ variables: {},
+ inline_helper_blocks: {},
+ inline_helper_modules: [],
+ helper_modules: [])
end
it "creates the template with the rendered content" do
- expect(IO.read(content.tempfile.path)).to eql <<EOF
-openldap
-default
-#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
-#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
-2
-helpers.erb
-#{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
-openldap
-default
-#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
-#{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
-2
-helpers.erb
-#{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
+ expect(IO.read(content.tempfile.path)).to eql <<~EOF
+ openldap
+ default
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
+ 2
+ helpers.erb
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
+ openldap
+ default
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb:2:in `from_file'
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/recipes/default.rb
+ 2
+ helpers.erb
+ #{CHEF_SPEC_DATA}/cookbooks/openldap/templates/default/helpers.erb
EOF
end
diff --git a/spec/unit/provider/template_spec.rb b/spec/unit/provider/template_spec.rb
index 306fd6ea71..a65846ecb2 100644
--- a/spec/unit/provider/template_spec.rb
+++ b/spec/unit/provider/template_spec.rb
@@ -26,7 +26,8 @@ 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(:run_context) { double("Chef::RunContext", :node => node, :events => events) }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:run_context) { double("Chef::RunContext", node: node, events: events, logger: logger) }
let(:enclosing_directory) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
@@ -49,7 +50,7 @@ describe Chef::Provider::Template do
end
let(:content) do
- content = double("Chef::Provider::File::Content::Template", :template_location => "/foo/bar/baz")
+ content = double("Chef::Provider::File::Content::Template", template_location: "/foo/bar/baz")
allow(File).to receive(:exists?).with("/foo/bar/baz").and_return(true)
content
end
@@ -58,9 +59,6 @@ describe Chef::Provider::Template do
context "when creating the template" do
- let(:node) { double("Chef::Node") }
- 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) do
canonicalize_path(File.expand_path(File.join(CHEF_SPEC_DATA, "templates")))
end
diff --git a/spec/unit/provider/user/aix_spec.rb b/spec/unit/provider/user/aix_spec.rb
index c70fdd9a57..f8b5b8a324 100644
--- a/spec/unit/provider/user/aix_spec.rb
+++ b/spec/unit/provider/user/aix_spec.rb
@@ -15,7 +15,6 @@
# limitations under the License.
#
-require "mixlib/shellout"
require "spec_helper"
describe Chef::Provider::User::Aix do
@@ -52,7 +51,7 @@ describe Chef::Provider::User::Aix do
end
it "should call chpasswd correctly" do
- expect(provider).to receive(:shell_out!).with("echo 'adam:Ostagazuzulum' | chpasswd -e").and_return true
+ expect(provider).to receive(:shell_out_compacted!).with("echo 'adam:Ostagazuzulum' | chpasswd -e").and_return true
provider.manage_user
end
end
@@ -61,7 +60,7 @@ describe Chef::Provider::User::Aix do
context "with a system user" do
before { new_resource.system(true) }
it "should add the user to the system group" do
- expect(provider).to receive(:shell_out!).with("useradd", "-g", "system", "adam")
+ expect(provider).to receive(:shell_out_compacted!).with("useradd", "-g", "system", "adam")
provider.create_user
end
end
@@ -74,13 +73,13 @@ describe Chef::Provider::User::Aix do
end
it "should create the home directory" do
- allow(provider).to receive(:shell_out!).with("usermod", "-d", "/home/adam", "adam")
+ allow(provider).to receive(:shell_out_compacted!).with("usermod", "-d", "/home/adam", "adam")
expect(FileUtils).to receive(:mkdir_p).and_return(true)
provider.manage_user
end
it "should move an existing home dir" do
- allow(provider).to receive(:shell_out!).with("usermod", "-d", "/mnt/home/adam", "adam")
+ allow(provider).to receive(:shell_out_compacted!).with("usermod", "-d", "/mnt/home/adam", "adam")
new_resource.home("/mnt/home/adam")
allow(File).to receive(:directory?).with("/home/adam").and_return(true)
expect(FileUtils).to receive(:mv).with("/home/adam", "/mnt/home/adam")
@@ -89,7 +88,7 @@ describe Chef::Provider::User::Aix do
it "should not pass -m" do
allow(FileUtils).to receive(:mkdir_p).and_return(true)
- expect(provider).to receive(:shell_out!).with("usermod", "-d", "/home/adam", "adam")
+ expect(provider).to receive(:shell_out_compacted!).with("usermod", "-d", "/home/adam", "adam")
provider.manage_user
end
end
diff --git a/spec/unit/provider/user/dscl_spec.rb b/spec/unit/provider/user/dscl_spec.rb
index f59709e717..c93a1eb4a8 100644
--- a/spec/unit/provider/user/dscl_spec.rb
+++ b/spec/unit/provider/user/dscl_spec.rb
@@ -18,7 +18,6 @@
require "spec_helper"
require "ostruct"
-require "mixlib/shellout"
describe Chef::Provider::User::Dscl do
before do
@@ -116,31 +115,31 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30"
describe "when shelling out to dscl" do
it "should run dscl with the supplied cmd /Path args" do
shell_return = shellcmdresult.new("stdout", "err", 0)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
expect(provider.run_dscl("cmd", "/Path", "args")).to eq("stdout")
end
it "returns an empty string from delete commands" do
shell_return = shellcmdresult.new("out", "err", 23)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-delete", "/Path", "args").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-delete", "/Path", "args").and_return(shell_return)
expect(provider.run_dscl("delete", "/Path", "args")).to eq("")
end
it "should raise an exception for any other command" do
shell_return = shellcmdresult.new("out", "err", 23)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-cmd", "/Path", "arguments").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-cmd", "/Path", "arguments").and_return(shell_return)
expect { provider.run_dscl("cmd", "/Path", "arguments") }.to raise_error(Chef::Exceptions::DsclCommandFailed)
end
it "raises an exception when dscl reports 'no such key'" do
shell_return = shellcmdresult.new("No such key: ", "err", 23)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
expect { provider.run_dscl("cmd", "/Path", "args") }.to raise_error(Chef::Exceptions::DsclCommandFailed)
end
it "raises an exception when dscl reports 'eDSRecordNotFound'" do
shell_return = shellcmdresult.new("<dscl_cmd> DS Error: -14136 (eDSRecordNotFound)", "err", -14136)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-cmd", "/Path", "args").and_return(shell_return)
expect { provider.run_dscl("cmd", "/Path", "args") }.to raise_error(Chef::Exceptions::DsclCommandFailed)
end
end
@@ -213,6 +212,32 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30"
end
end
+ describe "current_home_exists?" do
+ let(:current_resource) do
+ new_resource.dup
+ end
+
+ before do
+ provider.current_resource = current_resource
+ end
+
+ it "returns false for nil home dir" do
+ current_resource.home nil
+ expect(provider.current_home_exists?).to be_falsey
+ end
+
+ it "is false for empty string" do
+ current_resource.home ""
+ expect(provider.current_home_exists?).to be_falsey
+ end
+
+ it "is true for existing directory" do
+ current_resource.home "/Users/blah"
+ allow(::File).to receive(:exist?).with("/Users/blah").and_return(true)
+ expect(provider.current_home_exists?).to be_truthy
+ end
+ end
+
describe "when modifying the home directory" do
let(:current_resource) do
new_resource.dup
@@ -257,15 +282,8 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30"
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(:exist?).and_return(false, false, false)
- expect { provider.dscl_set_home }.to raise_error(Chef::Exceptions::User)
- end
-
- it "should run ditto to copy any missing files from skel to the new home dir" do
- expect(::File).to receive(:exist?).with("/System/Library/User\ Template/English.lproj").and_return(true)
- expect(FileUtils).to receive(:chown_R).with("toor", "", "/Users/toor")
- expect(provider).to receive(:shell_out!).with("ditto", "/System/Library/User Template/English.lproj", "/Users/toor")
+ it "should run createhomedir to create the user's new home folder" do
+ expect(provider).to receive(:shell_out_compacted!).with("/usr/sbin/createhomedir", "-c", "-u", "toor")
provider.ditto_home
end
@@ -380,8 +398,8 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30"
let(:user_plist_file) { nil }
before do
- expect(provider).to receive(:shell_out).with("dscacheutil", "-flushcache")
- expect(provider).to receive(:shell_out).with("plutil", "-convert", "xml1", "-o", "-", "/var/db/dslocal/nodes/Default/users/toor.plist") do
+ expect(provider).to receive(:shell_out_compacted).with("dscacheutil", "-flushcache")
+ expect(provider).to receive(:shell_out_compacted).with("plutil", "-convert", "xml1", "-o", "-", "/var/db/dslocal/nodes/Default/users/toor.plist") do
if user_plist_file.nil?
shellcmdresult.new("Can not find the file", "Sorry!!", 1)
else
@@ -724,7 +742,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30")
expect(provider).to receive(:prepare_password_shadow_info).and_return({})
mock_shellout = double("Mock::Shellout")
allow(mock_shellout).to receive(:run_command)
- expect(provider).to receive(:shell_out).and_return(mock_shellout)
+ expect(provider).to receive(:shell_out_compacted).and_return(mock_shellout)
expect(provider).to receive(:read_user_info)
expect(provider).to receive(:dscl_set)
expect(provider).to receive(:sleep).with(3)
@@ -793,7 +811,7 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30")
it "should raise an exception when the group does not exist" do
shell_return = shellcmdresult.new("<dscl_cmd> DS Error: -14136 (eDSRecordNotFound)", "err", -14136)
- expect(provider).to receive(:shell_out).with("dscl", ".", "-read", "/Groups/newgroup", "PrimaryGroupID").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted).with("dscl", ".", "-read", "/Groups/newgroup", "PrimaryGroupID").and_return(shell_return)
expect { provider.dscl_set_gid }.to raise_error(Chef::Exceptions::GroupIDNotFound)
end
end
@@ -848,8 +866,8 @@ ea18e18b720e358e7fbe3cfbeaa561456f6ba008937a30")
describe "when the user exists" do
before do
- expect(provider).to receive(:shell_out).with("dscacheutil", "-flushcache")
- expect(provider).to receive(:shell_out).with("plutil", "-convert", "xml1", "-o", "-", "/var/db/dslocal/nodes/Default/users/toor.plist") do
+ expect(provider).to receive(:shell_out_compacted).with("dscacheutil", "-flushcache")
+ expect(provider).to receive(:shell_out_compacted).with("plutil", "-convert", "xml1", "-o", "-", "/var/db/dslocal/nodes/Default/users/toor.plist") do
shellcmdresult.new(File.read(File.join(CHEF_SPEC_DATA, "mac_users/10.9.plist.xml")), "", 0)
end
provider.load_current_resource
diff --git a/spec/unit/provider/user/pw_spec.rb b/spec/unit/provider/user/pw_spec.rb
index 079fd44ef5..7c6948bf84 100644
--- a/spec/unit/provider/user/pw_spec.rb
+++ b/spec/unit/provider/user/pw_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Stephen Haynes (<sh@nomitor.com>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -81,12 +81,12 @@ describe Chef::Provider::User::Pw do
describe "create_user" do
before(:each) do
- allow(@provider).to receive(:shell_out!).and_return(true)
+ allow(@provider).to receive(:shell_out_compacted!).and_return(true)
allow(@provider).to receive(:modify_password).and_return(true)
end
it "should run pw useradd with the return of set_options" do
- expect(@provider).to receive(:shell_out!).with("pw", "useradd", "adam", "-m").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw", "useradd", "adam", "-m").and_return(true)
@provider.create_user
end
@@ -98,12 +98,12 @@ describe Chef::Provider::User::Pw do
describe "manage_user" do
before(:each) do
- allow(@provider).to receive(:shell_out!).and_return(true)
+ allow(@provider).to receive(:shell_out_compacted!).and_return(true)
allow(@provider).to receive(:modify_password).and_return(true)
end
it "should run pw usermod with the return of set_options" do
- expect(@provider).to receive(:shell_out!).with("pw", "usermod", "adam", "-m").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw", "usermod", "adam", "-m").and_return(true)
@provider.manage_user
end
@@ -116,12 +116,12 @@ describe Chef::Provider::User::Pw do
describe "remove_user" do
it "should run pw userdel with the new resources user name" do
@new_resource.manage_home false
- expect(@provider).to receive(:shell_out!).with("pw", "userdel", @new_resource.username).and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw", "userdel", @new_resource.username).and_return(true)
@provider.remove_user
end
it "should run pw userdel with the new resources user name and -r if manage_home is true" do
- expect(@provider).to receive(:shell_out!).with("pw", "userdel", @new_resource.username, "-r").and_return(true)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw", "userdel", @new_resource.username, "-r").and_return(true)
@provider.remove_user
end
end
@@ -140,14 +140,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(:shell_out!).with("pw", "lock", @new_resource.username)
+ expect(@provider).to receive(:shell_out_compacted!).with( "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(:shell_out!).with("pw", "unlock", @new_resource.username)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw", "unlock", @new_resource.username)
@provider.unlock_user
end
end
@@ -155,7 +155,7 @@ describe Chef::Provider::User::Pw do
describe "when modifying the password" do
before(:each) do
@status = double("Status", exitstatus: 0)
- allow(@provider).to receive(:shell_out!).and_return(@status)
+ allow(@provider).to receive(:shell_out_compacted!).and_return(@status)
end
describe "and the new password has not been specified" do
@@ -202,12 +202,12 @@ describe Chef::Provider::User::Pw do
end
it "should run pw usermod with the username and the option -H 0" do
- expect(@provider).to receive(:shell_out!).with("pw usermod adam -H 0", { :input => "abracadabra" }).and_return(@status)
+ expect(@provider).to receive(:shell_out_compacted!).with( "pw usermod adam -H 0", { input: "abracadabra" }).and_return(@status)
@provider.modify_password
end
it "should raise an exception if pw usermod fails" do
- expect(@provider).to receive(:shell_out!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
+ expect(@provider).to receive(:shell_out_compacted!).and_raise(Mixlib::ShellOut::ShellCommandFailed)
expect { @provider.modify_password }.to raise_error(Mixlib::ShellOut::ShellCommandFailed)
end
diff --git a/spec/unit/provider/user/solaris_spec.rb b/spec/unit/provider/user/solaris_spec.rb
index 1935336308..11c8656a5c 100644
--- a/spec/unit/provider/user/solaris_spec.rb
+++ b/spec/unit/provider/user/solaris_spec.rb
@@ -2,7 +2,7 @@
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: Daniel DeLeo (<dan@chef.io>)
# Author:: Dave Eddy (<dave@daveeddy.com>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# Copyright:: Copyright 2015-2016, Dave Eddy
#
# License:: Apache License, Version 2.0
@@ -20,7 +20,6 @@
# limitations under the License.
#
-require "mixlib/shellout"
require "spec_helper"
describe Chef::Provider::User::Solaris do
@@ -58,7 +57,7 @@ describe Chef::Provider::User::Solaris do
it "should use its own shadow file writer to set the password" do
expect(provider).to receive(:write_shadow_file)
- allow(provider).to receive(:shell_out!).and_return(true)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
provider.manage_user
end
@@ -68,8 +67,8 @@ describe Chef::Provider::User::Solaris do
password_file = Tempfile.new("shadow")
password_file.puts "adam:existingpassword:15441::::::"
password_file.close
- provider.password_file = password_file.path
- allow(provider).to receive(:shell_out!).and_return(true)
+ stub_const("Chef::Provider::User::Solaris::PASSWORD_FILE", password_file.path)
+ allow(provider).to receive(:shell_out_compacted!).and_return(true)
# may not be able to write to /etc for tests...
temp_file = Tempfile.new("shadow")
allow(Tempfile).to receive(:new).with("shadow", "/etc").and_return(temp_file)
@@ -84,7 +83,7 @@ describe Chef::Provider::User::Solaris do
context "with a system user" do
before { new_resource.system(true) }
it "should not pass -r" do
- expect(provider).to receive(:shell_out!).with("useradd", "adam")
+ expect(provider).to receive(:shell_out_compacted!).with( "useradd", "adam")
provider.create_user
end
end
@@ -92,7 +91,7 @@ describe Chef::Provider::User::Solaris do
context "with manage_home" do
before { new_resource.manage_home(true) }
it "should not pass -r" do
- expect(provider).to receive(:shell_out!).with("useradd", "-m", "adam")
+ expect(provider).to receive(:shell_out_compacted!).with( "useradd", "-m", "adam")
provider.create_user
end
end
@@ -162,7 +161,7 @@ describe Chef::Provider::User::Solaris do
describe "when locking the user" do
it "should run passwd -l with the new resources username" do
shell_return = shellcmdresult.new("", "", 0)
- expect(provider).to receive(:shell_out!).with("passwd", "-l", "adam").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted!).with("passwd", "-l", "adam").and_return(shell_return)
provider.lock_user
end
end
@@ -170,7 +169,7 @@ describe Chef::Provider::User::Solaris do
describe "when unlocking the user" do
it "should run passwd -u with the new resources username" do
shell_return = shellcmdresult.new("", "", 0)
- expect(provider).to receive(:shell_out!).with("passwd", "-u", "adam").and_return(shell_return)
+ expect(provider).to receive(:shell_out_compacted!).with("passwd", "-u", "adam").and_return(shell_return)
provider.unlock_user
end
end
diff --git a/spec/unit/provider/user/windows_spec.rb b/spec/unit/provider/user/windows_spec.rb
index 82f3c1ab2a..179926e5e6 100644
--- a/spec/unit/provider/user/windows_spec.rb
+++ b/spec/unit/provider/user/windows_spec.rb
@@ -28,11 +28,14 @@ class Chef
end
describe Chef::Provider::User::Windows do
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+
before(:each) do
@node = Chef::Node.new
@new_resource = Chef::Resource::User::WindowsUser.new("monkey")
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
+ allow(@run_context).to receive(:logger).and_return(logger)
@current_resource = Chef::Resource::User::WindowsUser.new("monkey")
@net_user = double("Chef::Util::Windows::NetUser")
diff --git a/spec/unit/provider/env_spec.rb b/spec/unit/provider/windows_env_spec.rb
index fd52c5a8ed..0e6cb02d48 100644
--- a/spec/unit/provider/env_spec.rb
+++ b/spec/unit/provider/windows_env_spec.rb
@@ -18,15 +18,16 @@
require "spec_helper"
-describe Chef::Provider::Env do
+describe Chef::Provider::WindowsEnv, :windows_only do
before do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
- @new_resource = Chef::Resource::Env.new("FOO")
+ @new_resource = Chef::Resource::WindowsEnv.new("FOO")
@new_resource.value("bar")
- @provider = Chef::Provider::Env.new(@new_resource, @run_context)
+ @new_resource.user("<System>")
+ @provider = Chef::Provider::WindowsEnv.new(@new_resource, @run_context)
end
it "assumes the key_name exists by default" do
@@ -35,8 +36,8 @@ describe Chef::Provider::Env do
describe "when loading the current status" do
before do
- #@current_resource = @new_resource.clone
- #Chef::Resource::Env.stub(:new).and_return(@current_resource)
+ # @current_resource = @new_resource.clone
+ # Chef::Resource::Env.stub(:new).and_return(@current_resource)
@provider.current_resource = @current_resource
allow(@provider).to receive(:env_value).with("FOO").and_return("bar")
allow(@provider).to receive(:env_key_exists).and_return(true)
@@ -47,12 +48,17 @@ describe Chef::Provider::Env do
expect(@provider.new_resource.name).to eq("FOO")
end
+ it "should create a current resource with the same user as the new resource" do
+ @provider.load_current_resource
+ expect(@provider.new_resource.user).to eq("<System>")
+ end
+
it "should set the key_name to the key name of the new resource" do
@provider.load_current_resource
expect(@provider.current_resource.key_name).to eq("FOO")
end
- it "should check if the key_name exists" do
+ it "should check if the key_name and user exist" do
expect(@provider).to receive(:env_key_exists).with("FOO").and_return(true)
@provider.load_current_resource
expect(@provider.key_exists).to be_truthy
@@ -65,7 +71,7 @@ describe Chef::Provider::Env do
end
it "should return the current resource" do
- expect(@provider.load_current_resource).to be_a_kind_of(Chef::Resource::Env)
+ expect(@provider.load_current_resource).to be_a_kind_of(Chef::Resource::WindowsEnv)
end
end
@@ -76,7 +82,7 @@ describe Chef::Provider::Env do
allow(@provider).to receive(:modify_env).and_return(true)
end
- it "should call create_env if the key does not exist" do
+ it "should call create_env if the key does not exist with user" do
expect(@provider).to receive(:create_env).and_return(true)
@provider.action_create
end
@@ -92,7 +98,7 @@ describe Chef::Provider::Env do
@provider.action_create
end
- it "should call modify_env if the key exists and values are not equal" do
+ it "should call modify_env if the key exists with provided user and values are not equal" do
@provider.key_exists = true
allow(@provider).to receive(:requires_modify_or_create?).and_return(true)
expect(@provider).to receive(:modify_env).and_return(true)
@@ -152,6 +158,12 @@ describe Chef::Provider::Env do
@provider.action_modify
end
+ it "should call modify_group if the key exists and users are not equal" do
+ expect(@provider).to receive(:requires_modify_or_create?).and_return(true)
+ expect(@provider).to receive(:modify_env).and_return(true)
+ @provider.action_modify
+ end
+
it "should set the new resources updated flag to true if modify_env is called" do
allow(@provider).to receive(:requires_modify_or_create?).and_return(true)
allow(@provider).to receive(:modify_env).and_return(true)
@@ -159,25 +171,26 @@ describe Chef::Provider::Env do
expect(@new_resource).to be_updated
end
- it "should not call modify_env if the key exists but the values are equal" do
+ it "should not call modify_env if the key exists with user but the values are equal" do
expect(@provider).to receive(:requires_modify_or_create?).and_return(false)
expect(@provider).not_to receive(:modify_env)
@provider.action_modify
end
- it "should raise a Chef::Exceptions::Env if the key doesn't exist" do
+ it "should raise a Chef::Exceptions::WindowsEnv if the key doesn't exist" do
@provider.key_exists = false
- expect { @provider.action_modify }.to raise_error(Chef::Exceptions::Env)
+ expect { @provider.action_modify }.to raise_error(Chef::Exceptions::WindowsEnv)
end
end
describe "delete_element" do
before(:each) do
- @current_resource = Chef::Resource::Env.new("FOO")
+ @current_resource = Chef::Resource::WindowsEnv.new("FOO")
@new_resource.delim ";"
@new_resource.value "C:/bar/bin"
+ @current_resource.user "<System>"
@current_resource.value "C:/foo/bin;C:/bar/bin"
@provider.current_resource = @current_resource
end
@@ -280,7 +293,7 @@ describe Chef::Provider::Env do
allow(@provider).to receive(:create_env).and_return(true)
@new_resource.delim ";"
- @current_resource = Chef::Resource::Env.new("FOO")
+ @current_resource = Chef::Resource::WindowsEnv.new("FOO")
@current_resource.value "C:/foo/bin"
@provider.current_resource = @current_resource
end
@@ -307,4 +320,81 @@ describe Chef::Provider::Env do
expect(@new_resource.value).to eq("C:/foo;C:/bar;C:/baz;C:/foo/bar")
end
end
+
+ context "when environment variable is not PATH" do
+ let(:new_resource) do
+ new_resource = Chef::Resource::WindowsEnv.new("CHEF_WINDOWS_ENV_TEST")
+ new_resource.value("foo")
+ new_resource
+ end
+ let(:provider) do
+ provider = Chef::Provider::WindowsEnv.new(new_resource, run_context)
+ allow(provider).to receive(:env_obj).and_return(double("null object").as_null_object)
+ provider
+ end
+
+ describe "action_create" do
+ before do
+ ENV.delete("CHEF_WINDOWS_ENV_TEST")
+ provider.key_exists = false
+ end
+
+ it "should update the ruby ENV object when it creates the key" do
+ provider.action_create
+ expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql("foo")
+ end
+ end
+
+ describe "action_modify" do
+ before do
+ ENV["CHEF_WINDOWS_ENV_TEST"] = "foo"
+ end
+
+ it "should update the ruby ENV object when it updates the value" do
+ expect(provider).to receive(:requires_modify_or_create?).and_return(true)
+ new_resource.value("foobar")
+ provider.action_modify
+ expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql("foobar")
+ end
+
+ describe "action_delete" do
+ before do
+ ENV["CHEF_WINDOWS_ENV_TEST"] = "foo"
+ end
+
+ it "should update the ruby ENV object when it deletes the key" do
+ provider.action_delete
+ expect(ENV["CHEF_WINDOWS_ENV_TEST"]).to eql(nil)
+ end
+ end
+ end
+ end
+
+ context "when environment is PATH" do
+ describe "for PATH" do
+ let(:system_root) { "%SystemRoot%" }
+ let(:system_root_value) { 'D:\Windows' }
+ let(:new_resource) do
+ new_resource = Chef::Resource::WindowsEnv.new("PATH")
+ new_resource.value(system_root)
+ new_resource
+ end
+ let(:provider) do
+ provider = Chef::Provider::WindowsEnv.new(new_resource, run_context)
+ allow(provider).to receive(:env_obj).and_return(double("null object").as_null_object)
+ provider
+ end
+
+ before do
+ stub_const("ENV", { "PATH" => "" })
+ end
+
+ it "replaces Windows system variables" do
+ expect(provider).to receive(:requires_modify_or_create?).and_return(true)
+ expect(provider).to receive(:expand_path).with(system_root).and_return(system_root_value)
+ provider.action_modify
+ expect(ENV["PATH"]).to eql(system_root_value)
+ end
+ end
+ end
end
diff --git a/spec/unit/provider/windows_task_spec.rb b/spec/unit/provider/windows_task_spec.rb
index abe90c6806..3a046ab5de 100644
--- a/spec/unit/provider/windows_task_spec.rb
+++ b/spec/unit/provider/windows_task_spec.rb
@@ -18,8 +18,9 @@
require "spec_helper"
-describe Chef::Provider::WindowsTask do
+describe Chef::Provider::WindowsTask, :windows_only do
let(:new_resource) { Chef::Resource::WindowsTask.new("sample_task") }
+ let(:current_resource) { Chef::Resource::WindowsTask.new() }
let(:provider) do
node = Chef::Node.new
@@ -28,405 +29,401 @@ describe Chef::Provider::WindowsTask do
Chef::Provider::WindowsTask.new(new_resource, run_context)
end
- let(:task_hash) do
- {
- :"" => "",
- :Folder => "\\",
- :HostName => "NIMISHA-PC",
- :TaskName => "\\sample_task",
- :NextRunTime => "3/30/2017 2:42:00 PM",
- :Status => "Ready",
- :LogonMode => "Interactive/Background",
- :LastRunTime => "3/30/2017 2:27:00 PM",
- :LastResult => "1",
- :Author => "Administrator",
- :TaskToRun => "chef-client",
- :StartIn => "N/A",
- :Comment => "N/A",
- :ScheduledTaskState => "Enabled",
- :IdleTime => "Disabled",
- :PowerManagement => "Stop On Battery Mode, No Start On Batteries",
- :RunAsUser => "SYSTEM",
- :DeleteTaskIfNotRescheduled => "Enabled",
- :StopTaskIfRunsXHoursandXMins => "72:00:00",
- :Schedule => "Scheduling data is not available in this format.",
- :ScheduleType => "One Time Only, Minute",
- :StartTime => "1:12:00 PM",
- :StartDate => "3/30/2017",
- :EndDate => "N/A",
- :Days => "N/A",
- :Months => "N/A",
- :"Repeat:Every" => "0 Hour(s), 15 Minute(s)",
- :"Repeat:Until:Time" => "None",
- :"Repeat:Until:Duration" => "Disabled",
- :"Repeat:StopIfStillRunning" => "Disabled",
- :run_level => "HighestAvailable",
- :repetition_interval => "PT15M",
- :execution_time_limit => "PT72H",
- }
- end
-
- let(:task_xml) do
- "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\r\r\n<Task version=\"1.2\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\r\r\n <RegistrationInfo>\r\r\n <Date>2017-03-31T15:34:44</Date>\r\r\n <Author>Administrator</Author>\r\r\n </RegistrationInfo>\r\r\n<Triggers>\r\r\n <TimeTrigger>\r\r\n <Repetition>\r\r\n <Interval>PT15M</Interval>\r\r\n <StopAtDurationEnd>false</StopAtDurationEnd>\r\r\n </Repetition>\r\r\n <StartBoundary>2017-03-31T15:34:00</StartBoundary>\r\r\n <Enabled>true</Enabled>\r\r\n </TimeTrigger>\r\r\n </Triggers>\r\r\n <Principals>\r\r\n <Principal id=\"Author\">\r\r\n <RunLevel>HighestAvailable</RunLevel>\r\r\n <UserId>S-1-5-18</UserId>\r\r\n </Principal>\r\r\n </Principals>\r\r\n <Settings>\r\r\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\r\r\n <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>\r\r\n <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>\r\r\n <AllowHardTerminate>true</AllowHardTerminate>\r\r\n <StartWhenAvailable>false</StartWhenAvailable>\r\r\n <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>\r\r\n <IdleSettings>\r\r\n <Duration>PT10M</Duration>\r\r\n<WaitTimeout>PT1H</WaitTimeout>\r\r\n <StopOnIdleEnd>true</StopOnIdleEnd>\r\r\n <RestartOnIdle>false</RestartOnIdle>\r\r\n </IdleSettings>\r\r\n <AllowStartOnDemand>true</AllowStartOnDemand>\r\r\n <Enabled>true</Enabled>\r\r\n <Hidden>false</Hidden>\r\r\n<RunOnlyIfIdle>false</RunOnlyIfIdle>\r\r\n <WakeToRun>false</WakeToRun>\r\r\n <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\r\r\n<Priority>7</Priority>\r\r\n </Settings>\r\r\n <Actions Context=\"Author\">\r\r\n <Exec>\r\r\n <Command>chef-client</Command>\r\r\n </Exec>\r\r\n </Actions>\r\r\n</Task>"
- end
-
describe "#load_current_resource" do
it "returns a current_resource" do
- allow(provider).to receive(:load_task_hash)
expect(provider.load_current_resource).to be_kind_of(Chef::Resource::WindowsTask)
end
+ end
- context "if the given task name already exists" do
- before do
- allow(provider).to receive(:load_task_hash).and_return({ :TaskName => "\\sample_task" })
- end
+ describe "#set_command_and_arguments" do
+ it "sets the command arguments if command has arguments passed in it" do
+ new_resource.command = "chef-client -W"
+ provider.send(:set_command_and_arguments)
+ expect(new_resource.command).to eq("chef-client")
+ expect(new_resource.command_arguments).to eq("-W")
+ end
+ end
- it "calls set_current_resource" do
- expect(provider).to receive(:set_current_resource)
- provider.load_current_resource
- end
+ describe "#set_start_day_and_time" do
+ it "sets the curret date and time start_day and start_time if nothing is provided by user" do
+ new_resource.start_day = nil
+ new_resource.start_time = nil
+ provider.send(:set_start_day_and_time)
+ expect(new_resource.start_day).not_to be_nil
+ expect(new_resource.start_time).not_to be_nil
end
- it "sets the attributes of current_resource" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- current_resource = provider.load_current_resource
- expect(current_resource.exists).to be(true)
- expect(current_resource.command).to eq("chef-client")
- expect(current_resource.user).to eq("SYSTEM")
- expect(current_resource.run_level).to eq(:highest)
- expect(current_resource.frequency).to eq(:minute)
- expect(current_resource.frequency_modifier).to eq(15)
- expect(current_resource.execution_time_limit).to eq("PT72H")
- expect(current_resource.enabled).to be(true)
+ it "does not set start_day and start_time if given by user" do
+ new_resource.start_day = "12/02/2017"
+ new_resource.start_time = "17:30"
+ provider.send(:set_start_day_and_time)
+ expect(new_resource.start_day).to eq("12/02/2017")
+ expect(new_resource.start_time).to eq("17:30")
end
end
- describe "#action_create" do
- it "doesn't create the same task if it's already existing" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- allow(provider).to receive(:task_need_update?).and_return(false)
- provider.run_action(:create)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- context "when task is not existing" do
- before do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- end
-
- it "creates the task if it's not already existing" do
- allow(provider).to receive(:task_need_update?).and_return(true)
- allow(provider).to receive(:basic_validation).and_return(true)
- expect(provider).to receive(:run_schtasks).with("CREATE", { "F" => "", "SC" => :hourly, "MO" => 1, "TR" => nil, "RU" => "SYSTEM" })
- provider.run_action(:create)
- expect(new_resource).to be_updated_by_last_action
- end
-
- it "updates the task XML if random_delay is provided" do
- new_resource.random_delay "20"
- allow(provider).to receive(:task_need_update?).and_return(true)
- allow(provider).to receive(:basic_validation).and_return(true)
- expect(provider).to receive(:run_schtasks).with("CREATE", { "F" => "", "SC" => :hourly, "MO" => 1, "TR" => nil, "RU" => "SYSTEM" })
- expect(provider).to receive(:update_task_xml)
- provider.run_action(:create)
- expect(new_resource).to be_updated_by_last_action
- end
-
- it "updates the task XML if execution_time_limit is provided" do
- new_resource.execution_time_limit "20"
- allow(provider).to receive(:task_need_update?).and_return(true)
- allow(provider).to receive(:basic_validation).and_return(true)
- expect(provider).to receive(:run_schtasks).with("CREATE", { "F" => "", "SC" => :hourly, "MO" => 1, "TR" => nil, "RU" => "SYSTEM" })
- expect(provider).to receive(:update_task_xml)
- provider.run_action(:create)
- expect(new_resource).to be_updated_by_last_action
- end
+ describe "#trigger" do
+ it "returns the trigger values in hash format" do
+ new_resource.start_day "12/02/2017"
+ new_resource.start_time "17:30"
+ new_resource.frequency :minute
+ new_resource.frequency_modifier 15
+ new_resource.random_delay 60
+ result = {
+ start_year: 2017,
+ start_month: 12,
+ start_day: 2,
+ start_hour: 17,
+ start_minute: 30,
+ end_month: 0,
+ end_day: 0,
+ end_year: 0,
+ trigger_type: 1,
+ type: { once: nil },
+ random_minutes_interval: 60,
+ minutes_interval: 15,
+ run_on_last_day_of_month: false,
+ run_on_last_week_of_month: false,
+
+ }
+ expect(provider.send(:trigger)).to eq(result)
end
end
- describe "#action_run" do
- it "does nothing if the task doesn't exist" do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- provider.run_action(:run)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- context "when the task exists" do
- it "does nothing if the task is already running" do
- task_hash[:Status] = "Running"
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- provider.run_action(:run)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- it "runs the task" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- expect(provider).to receive(:run_schtasks).with("RUN")
- provider.run_action(:run)
- expect(new_resource).to be_updated_by_last_action
- end
+ describe "#convert_hours_in_minutes" do
+ it "converts given hours in minutes" do
+ expect(provider.send(:convert_hours_in_minutes, 5)).to eq(300)
end
end
- describe "#action_delete" do
- it "deletes the task if it exists" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- expect(provider).to receive(:run_schtasks).with("DELETE", { "F" => "" })
- provider.run_action(:delete)
- expect(new_resource).to be_updated_by_last_action
+ describe "#trigger_type" do
+ it "returns 1 if frequency :once" do
+ new_resource.frequency :once
+ expect(provider.send(:trigger_type)).to eq(1)
end
- it "does nothing if the task doesn't exist" do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- provider.run_action(:delete)
- expect(new_resource).not_to be_updated_by_last_action
+ it "returns 2 if frequency :daily" do
+ new_resource.frequency :daily
+ expect(provider.send(:trigger_type)).to eq(2)
end
- end
- describe "#action_end" do
- it "does nothing if the task doesn't exist" do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- provider.run_action(:end)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- context "when the task exists" do
- it "does nothing if the task is not running" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- provider.run_action(:end)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- it "ends the task if it's running" do
- task_hash[:Status] = "Running"
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- expect(provider).to receive(:run_schtasks).with("END")
- provider.run_action(:end)
- expect(new_resource).to be_updated_by_last_action
- end
+ it "returns 3 if frequency :weekly" do
+ new_resource.frequency :weekly
+ expect(provider.send(:trigger_type)).to eq(3)
+ end
+
+ it "returns 4 if frequency :monthly" do
+ new_resource.frequency :monthly
+ expect(provider.send(:trigger_type)).to eq(4)
+ end
+
+ it "returns 5 if frequency :monthly and frequency_modifier is 'first, second'" do
+ new_resource.frequency :monthly
+ new_resource.frequency_modifier "first, second"
+ expect(provider.send(:trigger_type)).to eq(5)
+ end
+
+ it "returns 6 if frequency :on_idle" do
+ new_resource.frequency :on_idle
+ expect(provider.send(:trigger_type)).to eq(6)
+ end
+
+ it "returns 8 if frequency :onstart" do
+ new_resource.frequency :onstart
+ expect(provider.send(:trigger_type)).to eq(8)
+ end
+
+ it "returns 9 if frequency :on_logon" do
+ new_resource.frequency :on_logon
+ expect(provider.send(:trigger_type)).to eq(9)
end
end
- describe "#action_enable" do
- it "raises error if the task doesn't exist" do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- expect { provider.run_action(:enable) }.to raise_error(Errno::ENOENT)
- end
-
- context "when the task exists" do
- it "does nothing if the task is already enabled" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- provider.run_action(:enable)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- it "enables the task if it exists" do
- task_hash[:ScheduledTaskState] = "Disabled"
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- expect(provider).to receive(:run_schtasks).with("CHANGE", { "ENABLE" => "" })
- provider.run_action(:enable)
- expect(new_resource).to be_updated_by_last_action
- end
+ describe "#type" do
+ it "returns type hash when frequency :once" do
+ new_resource.frequency :once
+ new_resource.frequency_modifier 2
+ result = provider.send(:type)
+ expect(result).to include(:once)
+ expect(result).to eq({ once: nil })
+ end
+
+ it "returns type hash when frequency :daily" do
+ new_resource.frequency :daily
+ new_resource.frequency_modifier 2
+ result = provider.send(:type)
+ expect(result).to include(:days_interval)
+ expect(result).to eq({ days_interval: 2 })
+ end
+
+ it "returns type hash when frequency :weekly" do
+ new_resource.start_day "01/02/2018"
+ new_resource.frequency :weekly
+ new_resource.frequency_modifier 2
+ result = provider.send(:type)
+ expect(result).to include(:weeks_interval)
+ expect(result).to include(:days_of_week)
+ expect(result).to eq({ weeks_interval: 2, days_of_week: 4 })
+ end
+
+ it "returns type hash when frequency :monthly" do
+ new_resource.frequency :monthly
+ result = provider.send(:type)
+ expect(result).to include(:months)
+ expect(result).to include(:days)
+ expect(result).to eq({ months: 4095, days: 1 })
+ end
+
+ it "returns type hash when frequency :monthly with frequency_modifier 'first, second, third'" do
+ new_resource.start_day "01/02/2018"
+ new_resource.frequency :monthly
+ new_resource.frequency_modifier "First, Second, third"
+ result = provider.send(:type)
+ expect(result).to include(:months)
+ expect(result).to include(:days_of_week)
+ expect(result).to include(:weeks_of_month)
+ expect(result).to eq({ months: 4095, days_of_week: 4, weeks_of_month: 7 })
+ end
+
+ it "returns type hash when frequency :on_idle" do
+ new_resource.frequency :on_idle
+ result = provider.send(:type)
+ expect(result).to eq(nil)
+ end
+
+ it "returns type hash when frequency :onstart" do
+ new_resource.frequency :onstart
+ result = provider.send(:type)
+ expect(result).to eq(nil)
+ end
+
+ it "returns type hash when frequency :on_logon" do
+ new_resource.frequency :on_logon
+ result = provider.send(:type)
+ expect(result).to eq(nil)
end
end
- describe "#action_disable" do
- it "does nothing if the task doesn't exist" do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- provider.run_action(:disable)
- expect(new_resource).not_to be_updated_by_last_action
- end
-
- context "when the task exists" do
- it "disables the task if it's enabled" do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- expect(provider).to receive(:run_schtasks).with("CHANGE", { "DISABLE" => "" })
- provider.run_action(:disable)
- expect(new_resource).to be_updated_by_last_action
- end
-
- it "does nothing if the task is already disabled" do
- task_hash[:ScheduledTaskState] = "Disabled"
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
- provider.run_action(:disable)
- expect(new_resource).not_to be_updated_by_last_action
- end
+ describe "#weeks_of_month" do
+ it "returns the binary value 1 if frequency_modifier is set as 'first'" do
+ new_resource.frequency_modifier "first"
+ expect(provider.send(:weeks_of_month)).to eq(1)
+ end
+
+ it "returns the binary value 2 if frequency_modifier is set as 'second'" do
+ new_resource.frequency_modifier "second"
+ expect(provider.send(:weeks_of_month)).to eq(2)
+ end
+
+ it "returns the binary value 4 if frequency_modifier is set as 'third'" do
+ new_resource.frequency_modifier "third"
+ expect(provider.send(:weeks_of_month)).to eq(4)
+ end
+
+ it "returns the binary value 8 if frequency_modifier is set as 'fourth'" do
+ new_resource.frequency_modifier "fourth"
+ expect(provider.send(:weeks_of_month)).to eq(8)
+ end
+
+ it "returns the binary value 16 if frequency_modifier is set as 'last'" do
+ new_resource.frequency_modifier "last"
+ expect(provider.send(:weeks_of_month)).to eq(nil)
end
end
- describe "#run_schtasks" do
- before do
- @task_action = "CREATE"
- @options = { "F" => "", "SC" => :minute, "MO" => 15, "TR" => "chef-client", "RU" => "SYSTEM", "RL" => "HIGHEST" }
- @cmd = "schtasks /CREATE /TN \"sample_task\" /F /SC \"minute\" /MO \"15\" /TR \"chef-client\" /RU \"SYSTEM\" /RL \"HIGHEST\" "
+ describe "#weeks_of_month" do
+ it "returns the binary value 1 if frequency_modifier is set as 'first'" do
+ new_resource.frequency_modifier "first"
+ expect(provider.send(:weeks_of_month)).to eq(1)
+ end
+
+ it "returns the binary value 2 if frequency_modifier is set as 'second'" do
+ new_resource.frequency_modifier "second"
+ expect(provider.send(:weeks_of_month)).to eq(2)
end
- it "forms the command properly from the given options" do
- expect(provider).to receive(:shell_out!).with(@cmd, { :returns => [0] })
- provider.send(:run_schtasks, @task_action, @options)
+ it "returns the binary value 4 if frequency_modifier is set as 'third'" do
+ new_resource.frequency_modifier "third"
+ expect(provider.send(:weeks_of_month)).to eq(4)
+ end
+
+ it "returns the binary value 8 if frequency_modifier is set as 'fourth'" do
+ new_resource.frequency_modifier "fourth"
+ expect(provider.send(:weeks_of_month)).to eq(8)
+ end
+
+ it "returns the binary value 16 if frequency_modifier is set as 'last'" do
+ new_resource.frequency_modifier "last"
+ expect(provider.send(:weeks_of_month)).to eq(nil)
+ end
+
+ it "returns the binary value 15 if frequency_modifier is set as 'first, second, third, fourth'" do
+ new_resource.frequency_modifier "first, second, third, fourth"
+ expect(provider.send(:weeks_of_month)).to eq(15)
end
end
- describe "#basic_validation" do
- context "when command doesn't exist" do
- it "raise error" do
- new_resource.command ""
- expect { provider.send(:basic_validation) }.to raise_error(Chef::Exceptions::ValidationFailed)
- end
+ # REF: https://msdn.microsoft.com/en-us/library/windows/desktop/aa382063(v=vs.85).aspx
+ describe "#days_of_month" do
+ it "returns the binary value 1 if day is set as 1" do
+ new_resource.day "1"
+ expect(provider.send(:days_of_month)).to eq(1)
end
- context "when task_name doesn't exist" do
- let(:new_resource) { Chef::Resource::WindowsTask.new("") }
- it "raise error" do
- expect { provider.send(:basic_validation) }.to raise_error(Chef::Exceptions::ValidationFailed)
- end
+ it "returns the binary value 2 if day is set as 2" do
+ new_resource.day "2"
+ expect(provider.send(:days_of_month)).to eq(2)
end
- context "when task_name and command exists" do
- it "returns true" do
- new_resource.command "cd ~/"
- expect(provider.send(:basic_validation)).to be(true)
- end
+ it "returns the binary value 1073741824 if day is set as 31" do
+ new_resource.day "31"
+ expect(provider.send(:days_of_month)).to eq(1073741824)
+ end
+
+ it "returns the binary value 131072 if day is set as 18" do
+ new_resource.day "18"
+ expect(provider.send(:days_of_month)).to eq(131072)
end
end
- describe "#task_need_update?" do
- context "when task doesn't exist" do
- before do
- allow(provider).to receive(:load_task_hash)
- provider.load_current_resource
- end
-
- it "returns true" do
- new_resource.command "chef-client"
- expect(provider.send(:task_need_update?)).to be(true)
- end
- end
-
- context "when the task exists" do
- before do
- allow(provider).to receive(:load_task_hash).and_return(task_hash)
- provider.load_current_resource
-
- new_resource.command "chef-client"
- new_resource.run_level :highest
- new_resource.frequency :minute
- new_resource.frequency_modifier 15
- new_resource.user "SYSTEM"
- new_resource.execution_time_limit "PT72H"
- end
-
- context "when no attributes are modified" do
- it "returns false" do
- expect(provider.send(:task_need_update?)).to be(false)
- end
- end
-
- context "when frequency_modifier is updated" do
- it "returns true" do
- new_resource.frequency_modifier 25
- expect(provider.send(:task_need_update?)).to be(true)
- end
- end
-
- context "when months are updated" do
- it "returns true" do
- new_resource.months "JAN"
- expect(provider.send(:task_need_update?)).to be(true)
- end
- end
-
- context "when start_day is updated" do
- it "returns true" do
- new_resource.start_day "01/01/2000"
- expect(provider.send(:task_need_update?)).to be(true)
- end
- end
-
- context "when start_time updated" do
- it "returns true" do
- new_resource.start_time "01:01"
- expect(provider.send(:task_need_update?)).to be(true)
- end
- end
+ # Ref : https://msdn.microsoft.com/en-us/library/windows/desktop/aa380729(v=vs.85).aspx
+ describe "#days_of_week" do
+ it "returns the binary value 2 if day is set as 'Mon'" do
+ new_resource.day "Mon"
+ expect(provider.send(:days_of_week)).to eq(2)
+ end
+
+ it "returns the binary value 4 if day is set as 'Tue'" do
+ new_resource.day "Tue"
+ expect(provider.send(:days_of_week)).to eq(4)
+ end
+
+ it "returns the binary value 8 if day is set as 'Wed'" do
+ new_resource.day "Wed"
+ expect(provider.send(:days_of_week)).to eq(8)
+ end
+
+ it "returns the binary value 16 if day is set as 'Thu'" do
+ new_resource.day "Thu"
+ expect(provider.send(:days_of_week)).to eq(16)
+ end
+
+ it "returns the binary value 32 if day is set as 'Fri'" do
+ new_resource.day "Fri"
+ expect(provider.send(:days_of_week)).to eq(32)
+ end
+
+ it "returns the binary value 64 if day is set as 'Sat'" do
+ new_resource.day "Sat"
+ expect(provider.send(:days_of_week)).to eq(64)
+ end
+
+ it "returns the binary value 1 if day is set as 'Sun'" do
+ new_resource.day "Sun"
+ expect(provider.send(:days_of_week)).to eq(1)
+ end
+
+ it "returns the binary value 127 if day is set as 'Mon, tue, wed, thu, fri, sat, sun'" do
+ new_resource.day "Mon, tue, wed, thu, fri, sat, sun"
+ expect(provider.send(:days_of_week)).to eq(127)
end
end
- describe "#update_task_xml" do
- before do
- new_resource.command "chef-client"
- new_resource.run_level :highest
- new_resource.frequency :minute
- new_resource.frequency_modifier 15
- new_resource.user "SYSTEM"
- new_resource.random_delay "20"
+ # REf: https://msdn.microsoft.com/en-us/library/windows/desktop/aa382064(v=vs.85).aspx
+ describe "#monts_of_year" do
+ it "returns the binary value 1 if day is set as 'Jan'" do
+ new_resource.months "Jan"
+ expect(provider.send(:months_of_year)).to eq(1)
end
- it "does nothing if the task doesn't exist" do
- task_xml = double("xml", :exitstatus => 1)
- allow(provider).to receive(:powershell_out).and_return(task_xml)
- output = provider.send(:update_task_xml, ["random_delay"])
- expect(output).to be(nil)
+ it "returns the binary value 2 if day is set as 'Feb'" do
+ new_resource.months "Feb"
+ expect(provider.send(:months_of_year)).to eq(2)
end
- it "updates the task XML if random_delay is passed" do
- shell_out_obj = double("xml", :exitstatus => 0, :stdout => task_xml)
- allow(provider).to receive(:powershell_out).and_return(shell_out_obj)
- expect(::File).to receive(:join)
- expect(::File).to receive(:open)
- expect(::File).to receive(:delete)
- expect(provider).to receive(:run_schtasks).twice
- output = provider.send(:update_task_xml, ["random_delay"])
+ it "returns the binary value 4 if day is set as 'Mar'" do
+ new_resource.months "Mar"
+ expect(provider.send(:months_of_year)).to eq(4)
+ end
+
+ it "returns the binary value 8 if day is set as 'Apr'" do
+ new_resource.months "Apr"
+ expect(provider.send(:months_of_year)).to eq(8)
+ end
+
+ it "returns the binary value 16 if day is set as 'May'" do
+ new_resource.months "May"
+ expect(provider.send(:months_of_year)).to eq(16)
+ end
+
+ it "returns the binary value 32 if day is set as 'Jun'" do
+ new_resource.months "Jun"
+ expect(provider.send(:months_of_year)).to eq(32)
+ end
+
+ it "returns the binary value 64 if day is set as 'Jul'" do
+ new_resource.months "Jul"
+ expect(provider.send(:months_of_year)).to eq(64)
+ end
+
+ it "returns the binary value 128 if day is set as 'Aug'" do
+ new_resource.months "Aug"
+ expect(provider.send(:months_of_year)).to eq(128)
+ end
+
+ it "returns the binary value 256 if day is set as 'Sep'" do
+ new_resource.months "Sep"
+ expect(provider.send(:months_of_year)).to eq(256)
+ end
+
+ it "returns the binary value 512 if day is set as 'Oct'" do
+ new_resource.months "Oct"
+ expect(provider.send(:months_of_year)).to eq(512)
+ end
+
+ it "returns the binary value 1024 if day is set as 'Nov'" do
+ new_resource.months "Nov"
+ expect(provider.send(:months_of_year)).to eq(1024)
+ end
+
+ it "returns the binary value 2048 if day is set as 'Dec'" do
+ new_resource.months "Dec"
+ expect(provider.send(:months_of_year)).to eq(2048)
+ end
+
+ it "returns the binary value 4095 if day is set as 'jan, Feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec'" do
+ new_resource.months "jan, Feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec"
+ expect(provider.send(:months_of_year)).to eq(4095)
end
end
- describe "#load_task_hash" do
- it "returns false if the task doesn't exist" do
- allow(provider).to receive_message_chain(:powershell_out, :stdout, :force_encoding).and_return("")
- allow(provider).to receive(:load_task_xml)
- expect(provider.send(:load_task_hash, "chef-client")).to be(false)
+ describe "#run_level" do
+ it "return binary value 1 for run_level highest" do
+ new_resource.run_level :highest
+ expect(provider.send(:run_level)).to be(1)
end
- it "returns task hash if the task exists" do
- powershell_output = "\r\nFolder: \\\r\nHostName: NIMISHA-PC\r\nTaskName: \\chef-client\r\n"
- task_h = { :"" => "", :Folder => "\\", :HostName => "NIMISHA-PC", :TaskName => "\\chef-client" }
- allow(provider).to receive_message_chain(:powershell_out, :stdout, :force_encoding).and_return(powershell_output)
- allow(provider).to receive(:load_task_xml).with("chef-client")
- expect(provider.send(:load_task_hash, "chef-client")).to eq(task_h)
+ it "return binary value 1 for run_level limited" do
+ new_resource.run_level :limited
+ expect(provider.send(:run_level)).to be(0)
end
end
- describe "#frequency_modifier_allowed" do
- it "returns true for frequency :hourly" do
- new_resource.frequency :hourly
- expect(provider.send(:frequency_modifier_allowed)).to be(true)
+ describe "#logon_type" do
+ it "return logon_type bindary value as 5 as if password is nil" do
+ new_resource.password = nil
+ expect(provider.send(:logon_type)).to be(5)
end
- it "returns true for frequency :monthly if frequency_modifier is THIRD" do
- new_resource.frequency :monthly
- new_resource.frequency_modifier "THIRD"
- expect(provider.send(:frequency_modifier_allowed)).to be(true)
+ it "return logon_type bindary value as 1 as if password is not nil" do
+ new_resource.password = "abc"
+ expect(provider.send(:logon_type)).to be(1)
end
+ end
- it "returns false for frequency :once" do
- new_resource.frequency :once
- expect(provider.send(:frequency_modifier_allowed)).to be(false)
+ describe "#get_day" do
+ it "return day if date is provided" do
+ expect(provider.send(:get_day, "01/02/2018")).to eq("TUE")
end
end
end
diff --git a/spec/unit/provider/zypper_repository_spec.rb b/spec/unit/provider/zypper_repository_spec.rb
new file mode 100644
index 0000000000..df45c742d4
--- /dev/null
+++ b/spec/unit/provider/zypper_repository_spec.rb
@@ -0,0 +1,126 @@
+#
+# Author:: Tim Smith (<tsmith@chef.io>)
+# Copyright:: 2017-2018, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+# Output of the command:
+# => rpm -qa gpg-pubkey*
+RPM_KEYS = <<~EOF.freeze
+ gpg-pubkey-307e3d54-4be01a65
+ gpg-pubkey-3dbdc284-53674dd4
+EOF
+
+# Output of the command:
+# => gpg --with-fingerprint [FILE]
+GPG_FINGER = <<~EOF.freeze
+ pub 2048R/3DBDC284 2011-08-19 [expires: 2024-06-14]
+ Key fingerprint = 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62
+ uid nginx signing key <signing-key@nginx.com>
+EOF
+
+describe Chef::Provider::ZypperRepository do
+ let(:new_resource) { Chef::Resource::ZypperRepository.new("Nginx Repository") }
+ let(:logger) { double("Mixlib::Log::Child").as_null_object }
+ let(:provider) do
+ node = Chef::Node.new
+ events = Chef::EventDispatch::Dispatcher.new
+ run_context = Chef::RunContext.new(node, {}, events)
+ allow(run_context).to receive(:logger).and_return(logger)
+ Chef::Provider::ZypperRepository.new(new_resource, run_context)
+ end
+
+ let(:rpm_key_finger) do
+ double("shell_out", stdout: RPM_KEYS, exitstatus: 0, error?: false)
+ end
+
+ let(:gpg_finger) do
+ double("shell_out", stdout: GPG_FINGER, exitstatus: 0, error?: false)
+ end
+
+ it "responds to load_current_resource" do
+ expect(provider).to respond_to(:load_current_resource)
+ end
+
+ describe "#action_create" do
+ it "skips key import if gpgautoimportkeys is false" do
+ new_resource.gpgautoimportkeys(false)
+ expect(provider).to receive(:declare_resource)
+ expect(logger).to receive(:trace)
+ provider.run_action(:create)
+ end
+ end
+
+ describe "#escaped_repo_name" do
+ it "returns an escaped repo name" do
+ expect(provider.escaped_repo_name).to eq('Nginx\\ Repository')
+ end
+ end
+
+ describe "#cookbook_name" do
+ it "returns 'test' when the cookbook property is set" do
+ new_resource.cookbook("test")
+ expect(provider.cookbook_name).to eq("test")
+ end
+ end
+
+ describe "#key_type" do
+ it "returns :remote_file with an http URL" do
+ expect(provider.key_type("https://www.chef.io/key")).to eq(:remote_file)
+ end
+
+ it "returns :cookbook_file with a chef managed file" do
+ expect(provider).to receive(:has_cookbook_file?).and_return(true)
+ expect(provider.key_type("/foo/nginx.key")).to eq(:cookbook_file)
+ end
+
+ it "throws exception if an unknown file specified" do
+ expect(provider).to receive(:has_cookbook_file?).and_return(false)
+ expect { provider.key_type("/foo/nginx.key") }.to raise_error(Chef::Exceptions::FileNotFound)
+ end
+ end
+
+ describe "#key_installed?" do
+ before do
+ expect(provider).to receive(:shell_out).with("rpm -qa gpg-pubkey*").and_return(rpm_key_finger)
+ end
+
+ it "returns true if the key is installed" do
+ expect(provider).to receive(:key_fingerprint).and_return("3dbdc284")
+ expect(provider.key_installed?("/foo/nginx.key")).to be_truthy
+ end
+
+ it "returns false if the key is not installed" do
+ expect(provider).to receive(:key_fingerprint).and_return("BOGUS")
+ expect(provider.key_installed?("/foo/nginx.key")).to be_falsey
+ end
+ end
+
+ describe "#key_fingerprint" do
+ it "returns the key's fingerprint" do
+ expect(provider).to receive(:shell_out!).with("gpg --with-fingerprint /foo/nginx.key").and_return(gpg_finger)
+ expect(provider.key_fingerprint("/foo/nginx.key")).to eq("3dbdc284")
+ end
+ end
+
+ describe "#install_gpg_key" do
+ it "skips installing the key if a nil value for key is passed" do
+ expect(logger).to receive(:trace)
+ provider.install_gpg_key(nil)
+ end
+ end
+end
diff --git a/spec/unit/provider_resolver_spec.rb b/spec/unit/provider_resolver_spec.rb
index 1902fb5375..a3f2801adf 100644
--- a/spec/unit/provider_resolver_spec.rb
+++ b/spec/unit/provider_resolver_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Lamont Granquist (<lamont@chef.io>)
-# Copyright:: Copyright 2014-2016, Chef Software Inc.
+# Copyright:: Copyright 2014-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,7 +27,7 @@ require "fileutils"
include Chef::Mixin::ConvertToClassName
# Open up Provider so we can write things down easier in here
-#module Chef::Provider
+# module Chef::Provider
describe Chef::ProviderResolver do
include IntegrationSupport
@@ -428,7 +428,7 @@ describe Chef::ProviderResolver do
# old debian uses the Debian provider (does not have insserv or upstart, or update-rc.d???)
on_platform "debian", platform_version: "4.0", os: "linux" do
- #it_behaves_like "a debian platform using the debian provider"
+ # it_behaves_like "a debian platform using the debian provider"
end
# Debian replaced the debian provider with insserv in the FIXME:VERSION distro
@@ -553,15 +553,18 @@ describe Chef::ProviderResolver do
PROVIDERS =
{
+ aix_user: [ Chef::Resource::User::AixUser, Chef::Provider::User::Aix ],
+ apt_package: [ Chef::Resource::AptPackage, Chef::Provider::Package::Apt ],
bash: [ Chef::Resource::Bash, Chef::Provider::Script ],
+ bff_package: [ Chef::Resource::BffPackage, Chef::Provider::Package::Bff ],
breakpoint: [ Chef::Resource::Breakpoint, Chef::Resource::Breakpoint.action_class ],
chef_gem: [ Chef::Resource::ChefGem, Chef::Provider::Package::Rubygems ],
cookbook_file: [ Chef::Resource::CookbookFile, Chef::Provider::CookbookFile ],
csh: [ Chef::Resource::Csh, Chef::Provider::Script ],
- deploy: [ Chef::Resource::Deploy, Chef::Provider::Deploy::Timestamped ],
- deploy_revision: [ Chef::Resource::DeployRevision, Chef::Provider::Deploy::Revision ],
directory: [ Chef::Resource::Directory, Chef::Provider::Directory ],
- erl_call: [ Chef::Resource::ErlCall, Chef::Provider::ErlCall ],
+ dpkg_package: [ Chef::Resource::DpkgPackage, Chef::Provider::Package::Dpkg ],
+ dsc_script: [ Chef::Resource::DscScript, Chef::Provider::DscScript ],
+ dscl_user: [ Chef::Resource::User::DsclUser, Chef::Provider::User::Dscl ],
execute: [ Chef::Resource::Execute, Chef::Provider::Execute ],
file: [ Chef::Resource::File, Chef::Provider::File ],
gem_package: [ Chef::Resource::GemPackage, Chef::Provider::Package::Rubygems ],
@@ -570,53 +573,37 @@ describe Chef::ProviderResolver do
homebrew_package: [ Chef::Resource::HomebrewPackage, Chef::Provider::Package::Homebrew ],
http_request: [ Chef::Resource::HttpRequest, Chef::Provider::HttpRequest ],
ifconfig: [ Chef::Resource::Ifconfig, Chef::Provider::Ifconfig ],
+ ips_package: [ Chef::Resource::IpsPackage, Chef::Provider::Package::Ips ],
link: [ Chef::Resource::Link, Chef::Provider::Link ],
+ linux_user: [ Chef::Resource::User::LinuxUser, Chef::Provider::User::Linux ],
log: [ Chef::Resource::Log, Chef::Provider::Log::ChefLog ],
macports_package: [ Chef::Resource::MacportsPackage, Chef::Provider::Package::Macports ],
mdadm: [ Chef::Resource::Mdadm, Chef::Provider::Mdadm ],
mount: [ Chef::Resource::Mount, Chef::Provider::Mount::Mount ],
+ pacman_package: [ Chef::Resource::PacmanPackage, Chef::Provider::Package::Pacman ],
+ paludis_package: [ Chef::Resource::PaludisPackage, Chef::Provider::Package::Paludis ],
perl: [ Chef::Resource::Perl, Chef::Provider::Script ],
portage_package: [ Chef::Resource::PortagePackage, Chef::Provider::Package::Portage ],
+ pw_user: [ Chef::Resource::User::PwUser, Chef::Provider::User::Pw ],
python: [ Chef::Resource::Python, Chef::Provider::Script ],
remote_directory: [ Chef::Resource::RemoteDirectory, Chef::Provider::RemoteDirectory ],
route: [ Chef::Resource::Route, Chef::Provider::Route ],
- ruby: [ Chef::Resource::Ruby, Chef::Provider::Script ],
+ rpm_package: [ Chef::Resource::Package::RpmPackage, Chef::Provider::Package::Rpm ],
ruby_block: [ Chef::Resource::RubyBlock, Chef::Provider::RubyBlock ],
+ ruby: [ Chef::Resource::Ruby, Chef::Provider::Script ],
script: [ Chef::Resource::Script, Chef::Provider::Script ],
+ smartos_package: [ Chef::Resource::SmartosPackage, Chef::Provider::Package::SmartOS ],
+ solaris_package: [ Chef::Resource::SolarisPackage, Chef::Provider::Package::Solaris ],
+ solaris_user: [ Chef::Resource::User::SolarisUser, Chef::Provider::User::Solaris ],
subversion: [ Chef::Resource::Subversion, Chef::Provider::Subversion ],
template: [ Chef::Resource::Template, Chef::Provider::Template ],
- timestamped_deploy: [ Chef::Resource::TimestampedDeploy, Chef::Provider::Deploy::Timestamped ],
- aix_user: [ Chef::Resource::User::AixUser, Chef::Provider::User::Aix ],
- dscl_user: [ Chef::Resource::User::DsclUser, Chef::Provider::User::Dscl ],
- linux_user: [ Chef::Resource::User::LinuxUser, Chef::Provider::User::Linux ],
- pw_user: [ Chef::Resource::User::PwUser, Chef::Provider::User::Pw ],
- solaris_user: [ Chef::Resource::User::SolarisUser, Chef::Provider::User::Solaris ],
- windows_user: [ Chef::Resource::User::WindowsUser, Chef::Provider::User::Windows ],
whyrun_safe_ruby_block: [ Chef::Resource::WhyrunSafeRubyBlock, Chef::Provider::WhyrunSafeRubyBlock ],
-
- # We want to check that these are unsupported:
- apt_package: nil,
- bff_package: nil,
- dpkg_package: nil,
- dsc_script: nil,
- ips_package: nil,
- pacman_package: nil,
- paludis_package: nil,
- rpm_package: nil,
- smartos_package: nil,
- solaris_package: nil,
- yum_package: nil,
- windows_package: nil,
- windows_service: nil,
+ windows_package: [ Chef::Resource::WindowsPackage, Chef::Provider::Package::Windows ],
+ windows_service: [ Chef::Resource::WindowsService, Chef::Provider::Service::Windows ],
+ windows_user: [ Chef::Resource::User::WindowsUser, Chef::Provider::User::Windows ],
+ yum_package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
"linux" => {
- apt_package: [ Chef::Resource::AptPackage, Chef::Provider::Package::Apt ],
- dpkg_package: [ Chef::Resource::DpkgPackage, Chef::Provider::Package::Dpkg ],
- pacman_package: [ Chef::Resource::PacmanPackage, Chef::Provider::Package::Pacman ],
- paludis_package: [ Chef::Resource::PaludisPackage, Chef::Provider::Package::Paludis ],
- rpm_package: [ Chef::Resource::RpmPackage, Chef::Provider::Package::Rpm ],
- yum_package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
-
"debian" => {
ifconfig: [ Chef::Resource::Ifconfig, Chef::Provider::Ifconfig::Debian ],
package: [ Chef::Resource::AptPackage, Chef::Provider::Package::Apt ],
@@ -708,18 +695,21 @@ describe Chef::ProviderResolver do
"rhel" => {
# service: [ Chef::Resource::SystemdService, Chef::Provider::Service::Systemd ],
- package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
+ package: [ Chef::Resource::DnfPackage, Chef::Provider::Package::Dnf ],
ifconfig: [ Chef::Resource::Ifconfig, Chef::Provider::Ifconfig::Redhat ],
%w{amazon xcp xenserver ibm_powerkvm cloudlinux parallels} => {
"3.1.4" => {
+ package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
# service: [ Chef::Resource::RedhatService, Chef::Provider::Service::Redhat ],
},
},
%w{redhat centos scientific oracle} => {
"7.0" => {
+ package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
},
"6.0" => {
+ package: [ Chef::Resource::YumPackage, Chef::Provider::Package::Yum ],
# service: [ Chef::Resource::RedhatService, Chef::Provider::Service::Redhat ],
},
},
@@ -763,7 +753,7 @@ describe Chef::ProviderResolver do
"windows" => {
batch: [ Chef::Resource::Batch, Chef::Provider::Batch ],
dsc_script: [ Chef::Resource::DscScript, Chef::Provider::DscScript ],
- env: [ Chef::Resource::Env, Chef::Provider::Env::Windows ],
+ windows_env: [ Chef::Resource::WindowsEnv, Chef::Provider::WindowsEnv ],
group: [ Chef::Resource::Group, Chef::Provider::Group::Windows ],
mount: [ Chef::Resource::Mount, Chef::Provider::Mount::Windows ],
package: [ Chef::Resource::WindowsPackage, Chef::Provider::Package::Windows ],
@@ -782,13 +772,11 @@ describe Chef::ProviderResolver do
},
"aix" => {
- bff_package: [ Chef::Resource::BffPackage, Chef::Provider::Package::Aix ],
cron: [ Chef::Resource::Cron, Chef::Provider::Cron::Aix ],
group: [ Chef::Resource::Group, Chef::Provider::Group::Aix ],
ifconfig: [ Chef::Resource::Ifconfig, Chef::Provider::Ifconfig::Aix ],
mount: [ Chef::Resource::Mount, Chef::Provider::Mount::Aix ],
- # TODO should be Chef::Resource::BffPackage
- package: [ Chef::Resource::Package, Chef::Provider::Package::Aix ],
+ package: [ Chef::Resource::Package, Chef::Provider::Package::Bff ],
rpm_package: [ Chef::Resource::RpmPackage, Chef::Provider::Package::Rpm ],
user: [ Chef::Resource::User::AixUser, Chef::Provider::User::Aix ],
# service: [ Chef::Resource::AixService, Chef::Provider::Service::Aix ],
@@ -899,7 +887,7 @@ describe Chef::ProviderResolver do
},
},
},
- }
+ }.freeze
def self.create_provider_tests(providers, test, expected, filter)
expected = expected.merge(providers.select { |key, value| key.is_a?(Symbol) })
diff --git a/spec/unit/provider_spec.rb b/spec/unit/provider_spec.rb
index 6eb2bb9303..496871614a 100644
--- a/spec/unit/provider_spec.rb
+++ b/spec/unit/provider_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -75,10 +75,6 @@ describe Chef::Provider do
expect(@provider.respond_to?(:shell_out!)).to be true
end
- it "should mixin shell_out_with_systems_locale" do
- expect(@provider.respond_to?(:shell_out_with_systems_locale)).to be true
- end
-
it "should store the resource passed to new as new_resource" do
expect(@provider.new_resource).to eql(@resource)
end
@@ -197,7 +193,7 @@ describe Chef::Provider do
context "when using use_inline_resources" do
it "should log a deprecation warning" do
- pending Chef::VERSION.start_with?("13.6")
+ pending Chef::VERSION.start_with?("14.1")
expect(Chef).to receive(:deprecated).with(:use_inline_resources, kind_of(String))
Class.new(described_class) { use_inline_resources }
end
diff --git a/spec/unit/recipe_spec.rb b/spec/unit/recipe_spec.rb
index 7a538b721b..3b16edaa4a 100644
--- a/spec/unit/recipe_spec.rb
+++ b/spec/unit/recipe_spec.rb
@@ -3,7 +3,7 @@
# Author:: Christopher Walters (<cw@chef.io>)
# Author:: Tim Hinderliter (<tim@chef.io>)
# Author:: Seth Chisamore (<schisamo@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -110,7 +110,7 @@ describe Chef::Recipe do
it "locate resource for particular platform" do
ShaunTheSheep = Class.new(Chef::Resource)
ShaunTheSheep.resource_name :shaun_the_sheep
- ShaunTheSheep.provides :laughter, :platform => ["television"]
+ ShaunTheSheep.provides :laughter, platform: ["television"]
node.automatic[:platform] = "television"
node.automatic[:platform_version] = "123"
res = recipe.laughter "timmy"
@@ -141,16 +141,16 @@ describe Chef::Recipe do
Object.send(:remove_const, :TottenhamHotspur)
end
- it "selects the first one alphabetically" do
+ it "selects the last-writer wins" do
Sounders.provides :football, platform: "nbc_sports"
TottenhamHotspur.provides :football, platform: "nbc_sports"
res1 = recipe.football "club world cup"
expect(res1.name).to eql("club world cup")
- expect(res1).to be_a_kind_of(Sounders)
+ expect(res1).to be_a_kind_of(TottenhamHotspur)
end
- it "selects the first one alphabetically even if the declaration order is reversed" do
+ it "selects the last-writer wins even if the declaration order is reversed" do
TottenhamHotspur.provides :football2, platform: "nbc_sports"
Sounders.provides :football2, platform: "nbc_sports"
@@ -183,7 +183,7 @@ describe Chef::Recipe do
it "does not add the resource to the resource collection" do
zm_resource # force let binding evaluation
- expect { run_context.resource_collection.resources(:zen_master => "klopp") }.to raise_error(Chef::Exceptions::ResourceNotFound)
+ expect { run_context.resource_collection.resources(zen_master: "klopp") }.to raise_error(Chef::Exceptions::ResourceNotFound)
end
end
@@ -238,7 +238,7 @@ describe Chef::Recipe do
it "adds the resource to the resource collection" do
zm_resource # force let binding evaluation
- expect(run_context.resource_collection.resources(:zen_master => "klopp")).to eq(zm_resource)
+ expect(run_context.resource_collection.resources(zen_master: "klopp")).to eq(zm_resource)
end
it "will insert another resource if create_if_missing is not set (cloned resource as of Chef-12)" do
@@ -339,7 +339,7 @@ describe Chef::Recipe do
describe "resource definitions" do
it "should execute defined resources" do
crow_define = Chef::ResourceDefinition.new
- crow_define.define :crow, :peace => false, :something => true do
+ crow_define.define :crow, peace: false, something: true do
zen_master "lao tzu" do
peace params[:peace]
something params[:something]
@@ -349,13 +349,13 @@ describe Chef::Recipe do
recipe.crow "mine" do
peace true
end
- expect(run_context.resource_collection.resources(:zen_master => "lao tzu").name).to eql("lao tzu")
- expect(run_context.resource_collection.resources(:zen_master => "lao tzu").something).to eql(true)
+ expect(run_context.resource_collection.resources(zen_master: "lao tzu").name).to eql("lao tzu")
+ expect(run_context.resource_collection.resources(zen_master: "lao tzu").something).to eql(true)
end
it "should set the node on defined resources" do
crow_define = Chef::ResourceDefinition.new
- crow_define.define :crow, :peace => false, :something => true do
+ crow_define.define :crow, peace: false, something: true do
zen_master "lao tzu" do
peace params[:peace]
something params[:something]
@@ -366,12 +366,12 @@ describe Chef::Recipe do
recipe.crow "mine" do
something node[:foo]
end
- expect(recipe.resources(:zen_master => "lao tzu").something).to eql(false)
+ expect(recipe.resources(zen_master: "lao tzu").something).to eql(false)
end
it "should return the last statement in the definition as the retval" do
crow_define = Chef::ResourceDefinition.new
- crow_define.define :crow, :peace => false, :something => true do
+ crow_define.define :crow, peace: false, something: true do
"the return val"
end
run_context.definitions[:crow] = crow_define
@@ -392,7 +392,7 @@ describe Chef::Recipe do
end
CODE
expect { recipe.instance_eval(code) }.not_to raise_error
- expect(recipe.resources(:zen_master => "gnome").name).to eql("gnome")
+ expect(recipe.resources(zen_master: "gnome").name).to eql("gnome")
end
end
@@ -408,7 +408,7 @@ describe Chef::Recipe do
describe "from_file" do
it "should load a resource from a ruby file" do
recipe.from_file(File.join(CHEF_SPEC_DATA, "recipes", "test.rb"))
- res = recipe.resources(:file => "/etc/nsswitch.conf")
+ res = recipe.resources(file: "/etc/nsswitch.conf")
expect(res.name).to eql("/etc/nsswitch.conf")
expect(res.action).to eql([:create])
expect(res.owner).to eql("root")
@@ -426,7 +426,7 @@ describe Chef::Recipe do
expect(node).to receive(:loaded_recipe).with(:openldap, "gigantor")
allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
run_context.include_recipe "openldap::gigantor"
- res = run_context.resource_collection.resources(:cat => "blanket")
+ res = run_context.resource_collection.resources(cat: "blanket")
expect(res.name).to eql("blanket")
expect(res.pretty_kitty).to eql(false)
end
@@ -435,7 +435,7 @@ describe Chef::Recipe do
expect(node).to receive(:loaded_recipe).with(:openldap, "default")
allow(run_context).to receive(:unreachable_cookbook?).with(:openldap).and_return(false)
run_context.include_recipe "openldap"
- res = run_context.resource_collection.resources(:cat => "blanket")
+ res = run_context.resource_collection.resources(cat: "blanket")
expect(res.name).to eql("blanket")
expect(res.pretty_kitty).to eql(true)
end
diff --git a/spec/unit/resource/apt_package_spec.rb b/spec/unit/resource/apt_package_spec.rb
index 78eccfb444..66fe05ef33 100644
--- a/spec/unit/resource/apt_package_spec.rb
+++ b/spec/unit/resource/apt_package_spec.rb
@@ -31,8 +31,26 @@ describe Chef::Resource::AptPackage, "initialize" do
let(:resource) { Chef::Resource::AptPackage.new("foo") }
- it "should support default_release" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "supports default_release" do
resource.default_release("lenny-backports")
expect(resource.default_release).to eql("lenny-backports")
end
+
+ it "should preserve configuration files by default" do
+ expect(resource.overwrite_config_files).to eql(false)
+ end
end
diff --git a/spec/unit/resource/apt_preference_spec.rb b/spec/unit/resource/apt_preference_spec.rb
index 801434b4f3..c7ab8d2409 100644
--- a/spec/unit/resource/apt_preference_spec.rb
+++ b/spec/unit/resource/apt_preference_spec.rb
@@ -22,20 +22,36 @@ describe Chef::Resource::AptPreference do
let(:node) { Chef::Node.new }
let(:events) { Chef::EventDispatch::Dispatcher.new }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
- let(:resource) { Chef::Resource::AptPreference.new("libmysqlclient16", run_context) }
+ let(:resource) { Chef::Resource::AptPreference.new("fakey_fakerton", run_context) }
- it "should create a new Chef::Resource::AptPreference" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::AptPreference)
+ it "the package_name property is the name_property" do
+ expect(resource.package_name).to eql("fakey_fakerton")
end
- it "should resolve to a Noop class when apt-get is not found" do
- expect(Chef::Provider::AptPreference).to receive(:which).with("apt-get").and_return(false)
+ it "sets the default action as :add" do
+ expect(resource.action).to eql([:add])
+ end
+
+ it "supports :add, :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "resolves to a Noop class when on non-linux OS" do
+ node.automatic[:os] = "windows"
+ node.automatic[:platform_family] = "windows"
+ expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
+ end
+
+ it "resolves to a Noop class when on non-debian linux" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "gentoo"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a AptPreference class when apt-get is found" do
- expect(Chef::Provider::AptPreference).to receive(:which).with("apt-get").and_return(true)
+ it "resolves to a AptUpdate class when on a debian platform_family" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "debian"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::AptPreference)
end
end
diff --git a/spec/unit/resource/apt_repository_spec.rb b/spec/unit/resource/apt_repository_spec.rb
index 69cf94ae56..5b88d130f1 100644
--- a/spec/unit/resource/apt_repository_spec.rb
+++ b/spec/unit/resource/apt_repository_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Thom May (<thom@chef.io>)
-# Copyright:: Copyright (c) 2016 Chef Software, Inc.
+# Copyright:: 2016-2017, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,31 +20,73 @@ require "spec_helper"
describe Chef::Resource::AptRepository do
let(:node) { Chef::Node.new }
- let(:events) { Chef::EventDispatch::Dispatcher.new }
- let(:run_context) { Chef::RunContext.new(node, {}, events) }
- let(:resource) { Chef::Resource::AptRepository.new("multiverse", run_context) }
-
- it "should create a new Chef::Resource::AptRepository" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::AptRepository)
+ let(:run_context) do
+ node.automatic[:lsb][:codename] = "superduper"
+ empty_events = Chef::EventDispatch::Dispatcher.new
+ Chef::RunContext.new(node, {}, empty_events)
end
+ let(:resource) { Chef::Resource::AptRepository.new("fakey_fakerton", run_context) }
- it "the default keyserver should be keyserver.ubuntu.com" do
+ it "keyserver defaults to keyserver.ubuntu.com" do
expect(resource.keyserver).to eql("keyserver.ubuntu.com")
end
- it "the default distribution should be nillable" do
- expect(resource.distribution(nil)).to eql(nil)
- expect(resource.distribution).to eql(nil)
+ it "the repo_name property is the name_property" do
+ expect(resource.repo_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :add" do
+ expect(resource.action).to eql([:add])
+ end
+
+ it "supports :add, :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "distribution defaults to the distro codename" do
+ expect(resource.distribution).to eql("superduper")
+ end
+
+ it "allows setting key to an Array of keys and does not coerce it" do
+ resource.key = %w{key1 key2}
+ expect(resource.key).to eql(%w{key1 key2})
+ end
+
+ it "allows setting key to nil and does not coerce it" do
+ resource.key = nil
+ expect(resource.key).to be_nil
+ end
+
+ it "allows setting key to false and does not coerce it" do
+ resource.key = false
+ expect(resource.key).to be false
+ end
+
+ it "allows setting key to a String and coerces it to an Array" do
+ resource.key = "key1"
+ expect(resource.key).to eql(["key1"])
+ end
+
+ it "fails if the user provides a repo_name with a forward slash" do
+ expect { resource.repo_name "foo/bar" }.to raise_error(ArgumentError)
+ end
+
+ it "resolves to a Noop class when on non-linux OS" do
+ node.automatic[:os] = "windows"
+ node.automatic[:platform_family] = "windows"
+ expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a Noop class when apt-get is not found" do
- expect(Chef::Provider::AptRepository).to receive(:which).with("apt-get").and_return(false)
+ it "resolves to a Noop class when on non-debian linux" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "gentoo"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a AptRepository class when apt-get is found" do
- expect(Chef::Provider::AptRepository).to receive(:which).with("apt-get").and_return(true)
+ it "resolves to a AptUpdate class when on a debian platform_family" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "debian"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::AptRepository)
end
end
diff --git a/spec/unit/resource/apt_update_spec.rb b/spec/unit/resource/apt_update_spec.rb
index dd72b18063..d3a3c2d456 100644
--- a/spec/unit/resource/apt_update_spec.rb
+++ b/spec/unit/resource/apt_update_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Thom May (<thom@chef.io>)
-# Copyright:: Copyright (c) 2016 Chef Software, Inc.
+# Copyright:: 2016-2017, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,27 +24,39 @@ describe Chef::Resource::AptUpdate do
let(:run_context) { Chef::RunContext.new(node, {}, events) }
let(:resource) { Chef::Resource::AptUpdate.new("update", run_context) }
- it "should create a new Chef::Resource::AptUpdate" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::AptUpdate)
+ it "sets the default action as :periodic" do
+ expect(resource.action).to eql([:periodic])
end
- it "the default frequency should be 1 day" do
+ it "supports :periodic, :update actions" do
+ expect { resource.action :periodic }.not_to raise_error
+ expect { resource.action :update }.not_to raise_error
+ end
+
+ it "default frequency is set to be 1 day" do
expect(resource.frequency).to eql(86_400)
end
- it "the frequency should accept integers" do
+ it "frequency accepts integers" do
resource.frequency(400)
expect(resource.frequency).to eql(400)
end
- it "should resolve to a Noop class when apt-get is not found" do
- expect(Chef::Provider::AptUpdate).to receive(:which).with("apt-get").and_return(false)
+ it "resolves to a Noop class when on non-linux OS" do
+ node.automatic[:os] = "windows"
+ node.automatic[:platform_family] = "windows"
+ expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
+ end
+
+ it "resolves to a Noop class when on non-debian linux" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "gentoo"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a AptUpdate class when apt-get is found" do
- expect(Chef::Provider::AptUpdate).to receive(:which).with("apt-get").and_return(true)
+ it "resolves to a AptUpdate class when on a debian platform_family" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "debian"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::AptUpdate)
end
end
diff --git a/spec/unit/resource/bash_spec.rb b/spec/unit/resource/bash_spec.rb
index 56c36df1ce..6bd0f6df91 100644
--- a/spec/unit/resource/bash_spec.rb
+++ b/spec/unit/resource/bash_spec.rb
@@ -20,21 +20,26 @@ require "spec_helper"
describe Chef::Resource::Bash do
- before(:each) do
- @resource = Chef::Resource::Bash.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::Bash.new("fakey_fakerton") }
+
+ it "is a subclass of Chef::Resource::Script" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Script)
+ end
+
+ it "has a resource name of :bash" do
+ expect(resource.resource_name).to eql(:bash)
end
- it "should create a new Chef::Resource::Bash" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Bash)
+ it "has an interpreter of bash" do
+ expect(resource.interpreter).to eql("bash")
end
- it "should have a resource name of :bash" do
- expect(@resource.resource_name).to eql(:bash)
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
- it "should have an interpreter of bash" do
- expect(@resource.interpreter).to eql("bash")
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
end
end
diff --git a/spec/unit/resource/batch_spec.rb b/spec/unit/resource/batch_spec.rb
index e19ea15585..c161428a13 100644
--- a/spec/unit/resource/batch_spec.rb
+++ b/spec/unit/resource/batch_spec.rb
@@ -19,21 +19,18 @@
require "spec_helper"
describe Chef::Resource::Batch do
+ let(:node) { Chef::Node.new }
before(:each) do
- node = Chef::Node.new
-
node.default["kernel"] = Hash.new
node.default["kernel"][:machine] = :x86_64.to_s
node.automatic[:os] = "windows"
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
+ it "creates a new Chef::Resource::Batch" do
expect(@resource).to be_a_kind_of(Chef::Resource::Batch)
end
diff --git a/spec/unit/resource/bff_package_spec.rb b/spec/unit/resource/bff_package_spec.rb
new file mode 100644
index 0000000000..8862c8ecaf
--- /dev/null
+++ b/spec/unit/resource/bff_package_spec.rb
@@ -0,0 +1,51 @@
+#
+# Author:: Tim Smith (<tsmith@chef.io>)
+# Copyright:: Copyright 2018 Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "support/shared/unit/resource/static_provider_resolution"
+
+describe Chef::Resource::BffPackage, "initialize" do
+
+ static_provider_resolution(
+ resource: Chef::Resource::BffPackage,
+ provider: Chef::Provider::Package::Bff,
+ name: :bff_package,
+ action: :install,
+ os: "linux",
+ platform_family: "aix"
+ )
+
+end
+
+describe Chef::Resource::BffPackage, "defaults" do
+ let(:resource) { Chef::Resource::BffPackage.new("fakey_fakerton") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/breakpoint_spec.rb b/spec/unit/resource/breakpoint_spec.rb
index ce0df676dd..8b415fa8c1 100644
--- a/spec/unit/resource/breakpoint_spec.rb
+++ b/spec/unit/resource/breakpoint_spec.rb
@@ -48,12 +48,12 @@ describe Chef::Resource::Breakpoint do
provider.action_break
end
- it "allows the action :break" do
- expect(resource.allowed_actions).to include(:break)
+ it "sets the default action as :break" do
+ expect(resource.action).to eql([:break])
end
- it "defaults to the break action" do
- expect(resource.action).to eq([:break])
+ it "supports :break action" do
+ expect { resource.action :break }.not_to raise_error
end
it "names itself after the line number of the file where it's created" do
diff --git a/spec/unit/resource/build_essential_spec.rb b/spec/unit/resource/build_essential_spec.rb
new file mode 100644
index 0000000000..0043b08a5c
--- /dev/null
+++ b/spec/unit/resource/build_essential_spec.rb
@@ -0,0 +1,43 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::BuildEssential do
+
+ let(:resource) { Chef::Resource::BuildEssential.new("foo") }
+
+ it "has a resource name of :build_essential" do
+ expect(resource.resource_name).to eql(:build_essential)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install action" do
+ expect { resource.action :install }.not_to raise_error
+ end
+
+ context "when not settting a resource name" do
+ let(:resource) { Chef::Resource::BuildEssential.new(nil) }
+
+ it "the name defaults to an empty string" do
+ expect(resource.name).to eql("")
+ end
+ end
+end
diff --git a/spec/unit/resource/cab_package_spec.rb b/spec/unit/resource/cab_package_spec.rb
index aa4890f171..7e80abf41a 100644
--- a/spec/unit/resource/cab_package_spec.rb
+++ b/spec/unit/resource/cab_package_spec.rb
@@ -22,17 +22,43 @@ describe Chef::Resource::CabPackage do
let(:resource) { Chef::Resource::CabPackage.new("test_pkg") }
- it "creates a new Chef::Resource::CabPackage" do
- expect(resource).to be_a_kind_of(Chef::Resource)
+ it "is a subclass of Chef::Resource::Package" do
expect(resource).to be_a_kind_of(Chef::Resource::Package)
- expect(resource).to be_a_instance_of(Chef::Resource::CabPackage)
end
it "sets resource name as :cab_package" do
expect(resource.resource_name).to eql(:cab_package)
end
- it "coerce its name to a package_name" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "coerces name property to package_name property" do
expect(resource.package_name).to eql("test_pkg")
end
+
+ it "coerces name property to a source property if source not provided" do
+ expect(resource.source).to end_with("test_pkg")
+ end
+
+ it "coerces name property to a source property if source not provided and package_name is" do
+ resource.package_name("package.cab")
+ expect(resource.source).to end_with("package.cab")
+ end
+
+ it "coerces source property if it does not looks like a path" do
+ resource.source("package.cab")
+ expect(resource.source).not_to eq("package.cab")
+ end
end
diff --git a/spec/unit/resource/chef_gem_spec.rb b/spec/unit/resource/chef_gem_spec.rb
index 2b09fb388f..d4c94b0ac7 100644
--- a/spec/unit/resource/chef_gem_spec.rb
+++ b/spec/unit/resource/chef_gem_spec.rb
@@ -34,15 +34,29 @@ end
describe Chef::Resource::ChefGem, "gem_binary" do
let(:resource) { Chef::Resource::ChefGem.new("foo") }
- it "should raise an exception when gem_binary is set" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "raises an exception when gem_binary is set" do
expect { resource.gem_binary("/lol/cats/gem") }.to raise_error(ArgumentError)
end
- it "should set the gem_binary based on computing it from RbConfig" do
+ it "sets the gem_binary based on computing it from RbConfig" do
expect(resource.gem_binary).to eql("#{RbConfig::CONFIG['bindir']}/gem")
end
- it "should set compile_time to false by default" do
+ it "sets compile_time to false by default" do
expect(resource.compile_time).to be false
end
diff --git a/spec/unit/resource/chef_handler_spec.rb b/spec/unit/resource/chef_handler_spec.rb
new file mode 100644
index 0000000000..491b29ce28
--- /dev/null
+++ b/spec/unit/resource/chef_handler_spec.rb
@@ -0,0 +1,40 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::ChefHandler do
+
+ let(:resource) { Chef::Resource::ChefHandler.new("fakey_fakerton") }
+
+ it "has a resource name of :chef_handler" do
+ expect(resource.resource_name).to eql(:chef_handler)
+ end
+
+ it "the class_name property is the name_property" do
+ expect(resource.class_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :enable" do
+ expect(resource.action).to eql([:enable])
+ end
+
+ it "supports :disable, :enable actions" do
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/chocolatey_config_spec.rb b/spec/unit/resource/chocolatey_config_spec.rb
new file mode 100644
index 0000000000..3c50642487
--- /dev/null
+++ b/spec/unit/resource/chocolatey_config_spec.rb
@@ -0,0 +1,98 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::ChocolateyConfig do
+
+ let(:resource) { Chef::Resource::ChocolateyConfig.new("fakey_fakerton") }
+ let(:config) do
+ <<-CONFIG
+ <?xml version="1.0" encoding="utf-8"?>
+ <chocolatey xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <config>
+ <add key="containsLegacyPackageInstalls" value="true" description="Install has packages installed prior to 0.9.9 series." />
+ </config>
+ <sources>
+ <source id="chocolatey" value="https://chocolatey.org/api/v2/" disabled="false" bypassProxy="false" selfService="false" adminOnly="false" priority="0" />
+ </sources>
+ <features>
+ <feature name="checksumFiles" enabled="true" setExplicitly="false" description="Checksum files when pulled in from internet (based on package)." />
+ </features>
+ <apiKeys />
+ </chocolatey>
+CONFIG
+ end
+
+ # we save off the ENV and set ALLUSERSPROFILE so these specs will work on *nix and non-C drive Windows installs
+ before(:each) do
+ @original_env = ENV.to_hash
+ ENV["ALLUSERSPROFILE"] = 'C:\ProgramData'
+ end
+
+ after(:each) do
+ ENV.clear
+ ENV.update(@original_env)
+ end
+
+ it "has a resource name of :chocolatey_config" do
+ expect(resource.resource_name).to eql(:chocolatey_config)
+ end
+
+ it "is not a preview resource in Chef 15" do
+ pending("Chef 15") unless Chef::VERSION.start_with?("15")
+ expect(resource.class.preview_resource).to be_falsey
+ end
+
+ it "has a name property of config_key" do
+ expect(resource.config_key).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :set" do
+ expect(resource.action).to eql([:set])
+ end
+
+ it "supports :set and :unset actions" do
+ expect { resource.action :set }.not_to raise_error
+ expect { resource.action :unset }.not_to raise_error
+ end
+
+ it "bypass_proxy property defaults to false" do
+ expect { resource.bypass_proxy.to be_false }
+ end
+
+ describe "#fetch_config_element" do
+ it "raises and error if the config file cannot be found" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(false)
+ expect { resource.fetch_config_element("foo") }.to raise_error(RuntimeError)
+ end
+
+ it "returns the value if present in the config file" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(true)
+ allow(::File).to receive(:read).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(config)
+ expect(resource.fetch_config_element("containsLegacyPackageInstalls")).to eq("true")
+ expect { resource.fetch_config_element("foo") }.not_to raise_error
+ end
+
+ it "returns nil if the element is not present in the config file" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(true)
+ allow(::File).to receive(:read).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(config)
+ expect(resource.fetch_config_element("foo")).to be_nil
+ expect { resource.fetch_config_element("foo") }.not_to raise_error
+ end
+ end
+end
diff --git a/spec/unit/resource/chocolatey_package_spec.rb b/spec/unit/resource/chocolatey_package_spec.rb
index 9b433045c1..6dce2c0e69 100644
--- a/spec/unit/resource/chocolatey_package_spec.rb
+++ b/spec/unit/resource/chocolatey_package_spec.rb
@@ -22,50 +22,62 @@ describe Chef::Resource::ChocolateyPackage do
let(:resource) { Chef::Resource::ChocolateyPackage.new("fakey_fakerton") }
- it "should create a new Chef::Resource::ChocolateyPackage" do
- expect(resource).to be_a_kind_of(Chef::Resource)
+ it "is a subclass of Chef::Resource::Package" do
expect(resource).to be_a_kind_of(Chef::Resource::Package)
- expect(resource).to be_a_instance_of(Chef::Resource::ChocolateyPackage)
end
- it "should have a resource name of :python" do
+ it "has a resource name of :chocolatey_package" do
expect(resource.resource_name).to eql(:chocolatey_package)
end
- it "should coerce its name to a package_name array" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "coerces its name to a package_name array" do
expect(resource.package_name).to eql(["fakey_fakerton"])
end
- it "the package_name setter should coerce to arrays" do
+ it "the package_name setter coerces to arrays" do
resource.package_name("git")
expect(resource.package_name).to eql(["git"])
end
- it "the package_name setter should accept arrays" do
+ it "the package_name setter accepts arrays" do
resource.package_name(%w{git unzip})
expect(resource.package_name).to eql(%w{git unzip})
end
- it "the name should accept arrays" do
+ it "the name accepts arrays" do
resource = Chef::Resource::ChocolateyPackage.new(%w{git unzip})
expect(resource.package_name).to eql(%w{git unzip})
end
- it "the default version should be nil" do
+ it "the default version is nil" do
expect(resource.version).to eql(nil)
end
- it "the version setter should coerce to arrays" do
+ it "the version setter coerces to arrays" do
resource.version("1.2.3")
expect(resource.version).to eql(["1.2.3"])
end
- it "the version setter should accept arrays" do
+ it "the version setter accepts arrays" do
resource.version(["1.2.3", "4.5.6"])
expect(resource.version).to eql(["1.2.3", "4.5.6"])
end
- it "the default returns should be 0" do
+ it "the default returns is 0" do
expect(resource.returns).to eql([0])
end
diff --git a/spec/unit/resource/chocolatey_source_spec.rb b/spec/unit/resource/chocolatey_source_spec.rb
new file mode 100644
index 0000000000..237eb5b787
--- /dev/null
+++ b/spec/unit/resource/chocolatey_source_spec.rb
@@ -0,0 +1,102 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::ChocolateySource do
+
+ let(:resource) { Chef::Resource::ChocolateySource.new("fakey_fakerton") }
+ let(:config) do
+ <<-CONFIG
+ <?xml version="1.0" encoding="utf-8"?>
+ <chocolatey xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <config>
+ <add key="containsLegacyPackageInstalls" value="true" description="Install has packages installed prior to 0.9.9 series." />
+ </config>
+ <sources>
+ <source id="chocolatey" value="https://chocolatey.org/api/v2/" disabled="false" bypassProxy="false" selfService="false" adminOnly="false" priority="0" />
+ </sources>
+ <features>
+ <feature name="checksumFiles" enabled="true" setExplicitly="false" description="Checksum files when pulled in from internet (based on package)." />
+ </features>
+ <apiKeys />
+ </chocolatey>
+CONFIG
+ end
+
+ # we save off the ENV and set ALLUSERSPROFILE so these specs will work on *nix and non-C drive Windows installs
+ before(:each) do
+ @original_env = ENV.to_hash
+ ENV["ALLUSERSPROFILE"] = 'C:\ProgramData'
+ end
+
+ after(:each) do
+ ENV.clear
+ ENV.update(@original_env)
+ end
+
+ it "has a resource name of :chocolatey_source" do
+ expect(resource.resource_name).to eql(:chocolatey_source)
+ end
+
+ it "is not a preview resource in Chef 15" do
+ pending("Chef 15") unless Chef::VERSION.start_with?("15")
+ expect(resource.class.preview_resource).to be_falsey
+ end
+
+ it "has a name property of source_name" do
+ expect(resource.source_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :add" do
+ expect(resource.action).to eql([:add])
+ end
+
+ it "supports :add and :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "bypass_proxy property defaults to false" do
+ expect { resource.bypass_proxy.to be_false }
+ end
+
+ it "priority property defaults to 0" do
+ expect { resource.priority.to eq(0) }
+ end
+
+ describe "#fetch_source_element" do
+ it "raises and error if the config file cannot be found" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(false)
+ expect { resource.fetch_source_element("foo") }.to raise_error(RuntimeError)
+ end
+
+ it "returns the value if present in the config file" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(true)
+ allow(::File).to receive(:read).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(config)
+ expect(resource.fetch_source_element("chocolatey")["value"]).to eq("https://chocolatey.org/api/v2/")
+ expect { resource.fetch_source_element("foo") }.not_to raise_error
+ end
+
+ it "returns nil if the element is not present in the config file" do
+ allow(::File).to receive(:exist?).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(true)
+ allow(::File).to receive(:read).with('C:\ProgramData\chocolatey\config\chocolatey.config').and_return(config)
+ expect(resource.fetch_source_element("foo")).to be_nil
+ expect { resource.fetch_source_element("foo") }.not_to raise_error
+ end
+ end
+end
diff --git a/spec/unit/resource/conditional_spec.rb b/spec/unit/resource/conditional_spec.rb
index 0219945936..2a2e166e6c 100644
--- a/spec/unit/resource/conditional_spec.rb
+++ b/spec/unit/resource/conditional_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Daniel DeLeo (<dan@chef.io>)
-# Copyright:: Copyright 2011-2017, Chef Software Inc.
+# Copyright:: Copyright 2011-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,7 +22,7 @@ require "ostruct"
describe Chef::Resource::Conditional do
before do
allow_any_instance_of(Mixlib::ShellOut).to receive(:run_command).and_return(nil)
- @status = OpenStruct.new(:success? => true)
+ @status = OpenStruct.new(success?: true)
allow_any_instance_of(Mixlib::ShellOut).to receive(:status).and_return(@status)
@parent_resource = Chef::Resource.new("", Chef::Node.new)
end
@@ -92,14 +92,14 @@ describe Chef::Resource::Conditional do
describe "after running a command which timed out" do
before do
@conditional = Chef::Resource::Conditional.only_if(@parent_resource, "false")
- allow_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:shell_out_with_systems_locale).and_raise(Chef::Exceptions::CommandTimeout)
+ allow_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:shell_out).and_raise(Chef::Exceptions::CommandTimeout)
end
it "indicates that resource convergence should not continue" do
expect(@conditional.continue?).to be_falsey
end
- it "should log a warning" do
+ it "logs a warning" do
expect(Chef::Log).to receive(:warn).with("Command 'false' timed out")
@conditional.continue?
end
@@ -195,14 +195,14 @@ 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")
- allow_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:shell_out_with_systems_locale).and_raise(Chef::Exceptions::CommandTimeout)
+ allow_any_instance_of(Chef::GuardInterpreter::DefaultGuardInterpreter).to receive(:shell_out).and_raise(Chef::Exceptions::CommandTimeout)
end
it "indicates that resource convergence should continue" do
expect(@conditional.continue?).to be_truthy
end
- it "should log a warning" do
+ it "logs a warning" do
expect(Chef::Log).to receive(:warn).with("Command 'false' timed out")
@conditional.continue?
end
diff --git a/spec/unit/resource/cookbook_file_spec.rb b/spec/unit/resource/cookbook_file_spec.rb
index 05c37446a6..b35233649d 100644
--- a/spec/unit/resource/cookbook_file_spec.rb
+++ b/spec/unit/resource/cookbook_file_spec.rb
@@ -2,7 +2,7 @@
# Author:: Daniel DeLeo (<dan@chef.io>)
# Author:: Tyler Cloke (<tyler@chef.io>)
# Copyright:: Copyright 2010-2017, Chef Software Inc.
-#p License:: Apache License, Version 2.0
+# p License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -20,55 +20,60 @@
require "spec_helper"
describe Chef::Resource::CookbookFile do
- before do
- @cookbook_file = Chef::Resource::CookbookFile.new("sourcecode_tarball.tgz")
+ let(:resource) { Chef::Resource::CookbookFile.new("/foo/bar/sourcecode_tarball.tgz") }
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "uses the name parameter for the source parameter" do
- expect(@cookbook_file.name).to eq("sourcecode_tarball.tgz")
+ it "supports :create, :create_if_missing, :delete, :touch actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :touch }.not_to raise_error
end
- it "has a source parameter" do
- @cookbook_file.name("config_file.conf")
- expect(@cookbook_file.name).to eq("config_file.conf")
+ it "uses the basepath of the resource name for the source property" do
+ expect(resource.source).to eq("sourcecode_tarball.tgz")
end
- it "defaults to a nil cookbook parameter (current cookbook will be used)" do
- expect(@cookbook_file.cookbook).to be_nil
+ it "source property accepts Strings" do
+ resource.source("config_file.conf")
+ expect(resource.source).to eq("config_file.conf")
end
- it "has a cookbook parameter" do
- @cookbook_file.cookbook("munin")
- expect(@cookbook_file.cookbook).to eq("munin")
+ it "cookbook property defaults to nil (current cookbook will be used)" do
+ expect(resource.cookbook).to be_nil
end
- it "sets the provider to Chef::Provider::CookbookFile" do
- expect(@cookbook_file.provider).to eq(Chef::Provider::CookbookFile)
+ it "has a cookbook property that accepts Strings" do
+ resource.cookbook("munin")
+ expect(resource.cookbook).to eq("munin")
end
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")
+ resource.path("C:/temp/origin/file.txt")
+ resource.rights(:read, "Everyone")
+ resource.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")
+ resource.path("/tmp/origin/file.txt")
+ resource.group("wheel")
+ resource.mode("0664")
+ resource.owner("root")
+ resource.source("/tmp/foo.txt")
+ resource.cookbook("/tmp/cookbooks/cooked.rb")
end
- @cookbook_file.checksum("1" * 64)
+ resource.checksum("1" * 64)
end
it "describes the state" do
- state = @cookbook_file.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
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")
@@ -79,9 +84,9 @@ describe Chef::Resource::CookbookFile do
it "returns the path as its identity" do
if Chef::Platform.windows?
- expect(@cookbook_file.identity).to eq("C:/temp/origin/file.txt")
+ expect(resource.identity).to eq("C:/temp/origin/file.txt")
else
- expect(@cookbook_file.identity).to eq("/tmp/origin/file.txt")
+ expect(resource.identity).to eq("/tmp/origin/file.txt")
end
end
end
diff --git a/spec/unit/resource/cron_spec.rb b/spec/unit/resource/cron_spec.rb
index e2bfc321e8..11a9e9d524 100644
--- a/spec/unit/resource/cron_spec.rb
+++ b/spec/unit/resource/cron_spec.rb
@@ -20,157 +20,144 @@
require "spec_helper"
describe Chef::Resource::Cron do
+ let(:resource) { Chef::Resource::Cron.new("cronify") }
- before(:each) do
- @resource = Chef::Resource::Cron.new("cronify")
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should create a new Chef::Resource::Cron" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Cron)
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
end
- it "should have a name" do
- expect(@resource.name).to eql("cronify")
+ it "allows you to set a command" do
+ resource.command "/bin/true"
+ expect(resource.command).to eql("/bin/true")
end
- it "should have a default action of 'create'" do
- expect(@resource.action).to eql([:create])
+ it "allows you to set a user" do
+ resource.user "daemon"
+ expect(resource.user).to eql("daemon")
end
- it "should accept create or delete for action" do
- expect { @resource.action :create }.not_to raise_error
- expect { @resource.action :delete }.not_to raise_error
- expect { @resource.action :lolcat }.to raise_error(ArgumentError)
+ it "allows you to specify the minute" do
+ resource.minute "30"
+ expect(resource.minute).to eql("30")
end
- it "should allow you to set a command" do
- @resource.command "/bin/true"
- expect(@resource.command).to eql("/bin/true")
+ it "allows you to specify the hour" do
+ resource.hour "6"
+ expect(resource.hour).to eql("6")
end
- it "should allow you to set a user" do
- @resource.user "daemon"
- expect(@resource.user).to eql("daemon")
+ it "allows you to specify the day" do
+ resource.day "10"
+ expect(resource.day).to eql("10")
end
- it "should allow you to specify the minute" do
- @resource.minute "30"
- expect(@resource.minute).to eql("30")
+ it "allows you to specify the month" do
+ resource.month "10"
+ expect(resource.month).to eql("10")
end
- it "should allow you to specify the hour" do
- @resource.hour "6"
- expect(@resource.hour).to eql("6")
+ it "allows you to specify the weekday" do
+ resource.weekday "2"
+ expect(resource.weekday).to eql("2")
end
- it "should allow you to specify the day" do
- @resource.day "10"
- expect(@resource.day).to eql("10")
+ it "allows you to specify the mailto variable" do
+ resource.mailto "test@example.com"
+ expect(resource.mailto).to eql("test@example.com")
end
- it "should allow you to specify the month" do
- @resource.month "10"
- expect(@resource.month).to eql("10")
+ it "allows you to specify the path" do
+ resource.path "/usr/bin:/usr/sbin"
+ expect(resource.path).to eql("/usr/bin:/usr/sbin")
end
- it "should allow you to specify the weekday" do
- @resource.weekday "2"
- expect(@resource.weekday).to eql("2")
+ it "allows you to specify the home directory" do
+ resource.home "/root"
+ expect(resource.home).to eql("/root")
end
- it "should allow you to specify the mailto variable" do
- @resource.mailto "test@example.com"
- expect(@resource.mailto).to eql("test@example.com")
+ it "allows you to specify the shell to run the command with" do
+ resource.shell "/bin/zsh"
+ expect(resource.shell).to eql("/bin/zsh")
end
- it "should allow you to specify the path" do
- @resource.path "/usr/bin:/usr/sbin"
- expect(@resource.path).to eql("/usr/bin:/usr/sbin")
- end
-
- it "should allow you to specify the home directory" do
- @resource.home "/root"
- expect(@resource.home).to eql("/root")
- end
-
- it "should allow you to specify the shell to run the command with" do
- @resource.shell "/bin/zsh"
- expect(@resource.shell).to eql("/bin/zsh")
- end
-
- it "should allow you to specify environment variables hash" do
+ it "allows you to specify environment variables hash" do
env = { "TEST" => "LOL" }
- @resource.environment env
- expect(@resource.environment).to eql(env)
+ resource.environment env
+ expect(resource.environment).to eql(env)
end
- it "should allow * for all time and date values" do
+ it "allows * for all time and date values" do
%w{minute hour day month weekday}.each do |x|
- expect(@resource.send(x, "*")).to eql("*")
+ expect(resource.send(x, "*")).to eql("*")
end
end
- it "should allow ranges for all time and date values" do
+ it "allows ranges for all time and date values" do
%w{minute hour day month weekday}.each do |x|
- expect(@resource.send(x, "1-2,5")).to eql("1-2,5")
+ expect(resource.send(x, "1-2,5")).to eql("1-2,5")
end
end
- it "should have a default value of * for all time and date values" do
+ it "has a default value of * for all time and date values" do
%w{minute hour day month weekday}.each do |x|
- expect(@resource.send(x)).to eql("*")
+ expect(resource.send(x)).to eql("*")
end
end
- it "should have a default value of root for the user" do
- expect(@resource.user).to eql("root")
+ it "has a default value of root for the user" do
+ expect(resource.user).to eql("root")
end
- it "should reject any minute over 59" do
- expect { @resource.minute "60" }.to raise_error(RangeError)
+ it "rejects any minute over 59" do
+ expect { resource.minute "60" }.to raise_error(RangeError)
end
- it "should reject any hour over 23" do
- expect { @resource.hour "24" }.to raise_error(RangeError)
+ it "rejects any hour over 23" do
+ expect { resource.hour "24" }.to raise_error(RangeError)
end
- it "should reject any day over 31" do
- expect { @resource.day "32" }.to raise_error(RangeError)
+ it "rejects any day over 31" do
+ expect { resource.day "32" }.to raise_error(RangeError)
end
- it "should reject any month over 12" do
- expect { @resource.month "13" }.to raise_error(RangeError)
+ it "rejects any month over 12" do
+ expect { resource.month "13" }.to raise_error(RangeError)
end
describe "weekday" do
- it "should reject any weekday over 7" do
- expect { @resource.weekday "8" }.to raise_error(RangeError)
+ it "rejects any weekday over 7" do
+ expect { resource.weekday "8" }.to raise_error(RangeError)
end
- it "should reject any symbols which don't represent day of week" do
- expect { @resource.weekday :foo }.to raise_error(RangeError)
+ it "rejects any symbols which don't represent day of week" do
+ expect { resource.weekday :foo }.to raise_error(RangeError)
end
end
- it "should convert integer schedule values to a string" do
+ it "converts integer schedule values to a string" do
%w{minute hour day month weekday}.each do |x|
- expect(@resource.send(x, 5)).to eql("5")
+ expect(resource.send(x, 5)).to eql("5")
end
end
describe "when it has a time (minute, hour, day, month, weeekend) and user" do
before do
- @resource.command("tackle")
- @resource.minute("1")
- @resource.hour("2")
- @resource.day("3")
- @resource.month("4")
- @resource.weekday("5")
- @resource.user("root")
+ resource.command("tackle")
+ resource.minute("1")
+ resource.hour("2")
+ resource.day("3")
+ resource.month("4")
+ resource.weekday("5")
+ resource.user("root")
end
it "describes the state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:minute]).to eq("1")
expect(state[:hour]).to eq("2")
expect(state[:day]).to eq("3")
@@ -180,7 +167,7 @@ describe Chef::Resource::Cron do
end
it "returns the command as its identity" do
- expect(@resource.identity).to eq("tackle")
+ expect(resource.identity).to eq("tackle")
end
end
end
diff --git a/spec/unit/resource/csh_spec.rb b/spec/unit/resource/csh_spec.rb
index 864175fc85..cdb6ecec2a 100644
--- a/spec/unit/resource/csh_spec.rb
+++ b/spec/unit/resource/csh_spec.rb
@@ -20,21 +20,26 @@ require "spec_helper"
describe Chef::Resource::Csh do
- before(:each) do
- @resource = Chef::Resource::Csh.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::Csh.new("fakey_fakerton") }
+
+ it "is a subclass of Chef::Resource::Script" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Script)
+ end
+
+ it "has a resource name of :csh" do
+ expect(resource.resource_name).to eql(:csh)
end
- it "should create a new Chef::Resource::Csh" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Csh)
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
- it "should have a resource name of :csh" do
- expect(@resource.resource_name).to eql(:csh)
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
end
- it "should have an interpreter of csh" do
- expect(@resource.interpreter).to eql("csh")
+ it "has an interpreter of csh" do
+ expect(resource.interpreter).to eql("csh")
end
end
diff --git a/spec/unit/resource/deploy_spec.rb b/spec/unit/resource/deploy_spec.rb
deleted file mode 100644
index e008d79c29..0000000000
--- a/spec/unit/resource/deploy_spec.rb
+++ /dev/null
@@ -1,283 +0,0 @@
-#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-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,
- name: :deploy,
- 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)
- end
- end
-
- 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])
- expect(@resource.send(attr_name)).to eql( !opts[:defaults_to] )
- end
- end
-
- 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)).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)).to eq(callback_file)
- expect { @resource.send(attr_name, :this_is_fail) }.to raise_error(ArgumentError)
- end
- end
- end
-
- before do
- @resource = Chef::Resource::Deploy.new("/my/deploy/dir")
- end
-
- resource_has_a_string_attribute(:repo)
- resource_has_a_string_attribute(:deploy_to)
- resource_has_a_string_attribute(:role)
- resource_has_a_string_attribute(:restart_command)
- resource_has_a_string_attribute(:migration_command)
- resource_has_a_string_attribute(:user)
- resource_has_a_string_attribute(:group)
- resource_has_a_string_attribute(:repository_cache)
- resource_has_a_string_attribute(:copy_exclude)
- resource_has_a_string_attribute(:revision)
- resource_has_a_string_attribute(:remote)
- resource_has_a_string_attribute(:git_ssh_wrapper)
- resource_has_a_string_attribute(:svn_username)
- resource_has_a_string_attribute(:svn_password)
- 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)
-
- it "uses the first argument as the deploy directory" do
- expect(@resource.deploy_to).to eql("/my/deploy/dir")
- end
-
- # For git, any revision, branch, tag, whatever is resolved to a SHA1 ref.
- # For svn, the branch is included in the repo URL.
- # Therefore, revision and branch ARE NOT SEPARATE THINGS
- it "aliases #revision as #branch" do
- @resource.branch "stable"
- expect(@resource.revision).to eql("stable")
- end
-
- it "takes the SCM resource to use as a constant, and defaults to git" do
- expect(@resource.scm_provider).to eql(Chef::Provider::Git)
- @resource.scm_provider Chef::Provider::Subversion
- expect(@resource.scm_provider).to eql(Chef::Provider::Subversion)
- end
-
- it "allows scm providers to be set via symbol" do
- expect(@resource.scm_provider).to eq(Chef::Provider::Git)
- @resource.scm_provider :subversion
- expect(@resource.scm_provider).to eq(Chef::Provider::Subversion)
- end
-
- it "allows scm providers to be set via string" do
- expect(@resource.scm_provider).to eq(Chef::Provider::Git)
- @resource.scm_provider "subversion"
- expect(@resource.scm_provider).to eq(Chef::Provider::Subversion)
- end
-
- it "has a boolean attribute for svn_force_export defaulting to false" 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)
- end
-
- it "takes arbitrary environment variables in a hash" do
- @resource.environment "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" })
- end
-
- it "sets destination to $deploy_to/shared/$repository_cache" do
- expect(@resource.destination).to eql("/my/deploy/dir/shared/cached-copy")
- end
-
- it "sets shared_path to $deploy_to/shared" do
- expect(@resource.shared_path).to eql("/my/deploy/dir/shared")
- end
-
- it "sets current_path to $deploy_to/current" do
- expect(@resource.current_path).to eql("/my/deploy/dir/current")
- end
-
- it "gets the current_path correct even if the shared_path is set (regression test)" do
- @resource.shared_path
- expect(@resource.current_path).to eql("/my/deploy/dir/current")
- end
-
- it "allows depth to be set via integer" do
- expect(@resource.depth).to be_nil
- @resource.depth 1
- expect(@resource.depth).to eql(1)
- end
-
- it "gives #depth as 5 if shallow clone is true, nil otherwise" do
- expect(@resource.depth).to be_nil
- @resource.shallow_clone true
- expect(@resource.depth).to eql(5)
- end
-
- it "aliases repo as repository" do
- @resource.repository "git@github.com/opcode/cookbooks.git"
- expect(@resource.repo).to eql("git@github.com/opcode/cookbooks.git")
- end
-
- it "aliases git_ssh_wrapper as ssh_wrapper" do
- @resource.ssh_wrapper "git_my_repo.sh"
- expect(@resource.git_ssh_wrapper).to eql("git_my_repo.sh")
- end
-
- it "has an Array attribute purge_before_symlink, default: log, tmp/pids, public/system" do
- expect(@resource.purge_before_symlink).to eq(%w{ log tmp/pids public/system })
- @resource.purge_before_symlink %w{foo bar baz}
- expect(@resource.purge_before_symlink).to eq(%w{foo bar baz})
- end
-
- it "has an Array attribute create_dirs_before_symlink, default: tmp, public, config" do
- expect(@resource.create_dirs_before_symlink).to eq(%w{tmp public config})
- @resource.create_dirs_before_symlink %w{foo bar baz}
- expect(@resource.create_dirs_before_symlink).to eq(%w{foo bar baz})
- 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" }
- expect(@resource.symlinks).to eq(default)
- @resource.symlinks "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" })
- @resource.symlink_before_migrate "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
- resource_has_a_callback_attribute :before_symlink
- resource_has_a_callback_attribute :before_restart
- resource_has_a_callback_attribute :after_restart
-
- it "aliases restart_command as restart" do
- @resource.restart "foobaz"
- expect(@resource.restart_command).to eq("foobaz")
- end
-
- it "takes a block for the restart parameter" do
- restart_like_this = lambda { p :noop }
- @resource.restart(&restart_like_this)
- expect(@resource.restart).to eq(restart_like_this)
- end
-
- it "allows providers to be set with a full class name" do
- @resource.provider Chef::Provider::Deploy::Timestamped
- expect(@resource.provider).to eq(Chef::Provider::Deploy::Timestamped)
- end
-
- it "allows deploy providers to be set via symbol" do
- @resource.provider :deploy_revision
- expect(@resource.provider).to eq(Chef::Provider::Deploy::Revision)
- end
-
- it "allows deploy providers to be set via string" do
- @resource.provider "deploy_revision"
- expect(@resource.provider).to eq(Chef::Provider::Deploy::Revision)
- end
-
- it "defaults keep_releases to 5" do
- expect(@resource.keep_releases).to eq(5)
- end
-
- it "allows keep_releases to be set via integer" do
- @resource.keep_releases 10
- expect(@resource.keep_releases).to eq(10)
- end
-
- it "enforces a minimum keep_releases of 1" do
- @resource.keep_releases 0
- expect(@resource.keep_releases).to eq(1)
- end
-
- describe "when it has a timeout attribute" do
- let(:ten_seconds) { 10 }
- before { @resource.timeout(ten_seconds) }
- it "stores this timeout" do
- expect(@resource.timeout).to eq(ten_seconds)
- end
- end
-
- describe "when it has no timeout attribute" do
- it "should have no default timeout" do
- expect(@resource.timeout).to be_nil
- end
- end
-
- describe "when it has meta application root, revision, user, group,
- scm provider, repository cache, environment, simlinks and migrate" do
- before do
- @resource.repository("http://uri.org")
- @resource.deploy_to("/")
- @resource.revision("1.2.3")
- @resource.user("root")
- @resource.group("pokemon")
- @resource.scm_provider(Chef::Provider::Git)
- @resource.repository_cache("cached-copy")
- @resource.environment({ "SUDO" => "TRUE" })
- @resource.symlinks({ "system" => "public/system" })
- @resource.migrate(false)
-
- end
-
- it "describes its state" do
- state = @resource.state_for_resource_reporter
- expect(state[:deploy_to]).to eq("/")
- expect(state[:revision]).to eq("1.2.3")
- end
-
- it "returns the repository URI as its identity" 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 b3a0134024..3dd68211db 100644
--- a/spec/unit/resource/directory_spec.rb
+++ b/spec/unit/resource/directory_spec.rb
@@ -20,63 +20,50 @@
require "spec_helper"
describe Chef::Resource::Directory do
+ let(:resource) { Chef::Resource::Directory.new("fakey_fakerton") }
- before(:each) do
- @resource = Chef::Resource::Directory.new("fakey_fakerton")
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
end
- it "should create a new Chef::Resource::Directory" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Directory)
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should have a name" do
- expect(@resource.name).to eql("fakey_fakerton")
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
end
- it "should have a default action of 'create'" do
- expect(@resource.action).to eql([:create])
+ it "accepts a string as the path" do
+ expect { resource.path "/tmp" }.not_to raise_error
+ expect(resource.path).to eql("/tmp")
+ expect { resource.path Hash.new }.to raise_error(ArgumentError)
end
- it "should accept create or delete for action" do
- expect { @resource.action :create }.not_to raise_error
- expect { @resource.action :delete }.not_to raise_error
- expect { @resource.action :blues }.to raise_error(ArgumentError)
- end
-
- it "should use the object name as the path by default" do
- expect(@resource.path).to eql("fakey_fakerton")
- end
-
- it "should accept a string as the path" do
- expect { @resource.path "/tmp" }.not_to raise_error
- expect(@resource.path).to eql("/tmp")
- expect { @resource.path Hash.new }.to raise_error(ArgumentError)
- end
-
- it "should allow you to have specify whether the action is recursive with true/false" do
- expect { @resource.recursive true }.not_to raise_error
- expect { @resource.recursive false }.not_to raise_error
- expect { @resource.recursive "monkey" }.to raise_error(ArgumentError)
+ it "allows you to have specify whether the action is recursive with true/false" do
+ expect { resource.recursive true }.not_to raise_error
+ expect { resource.recursive false }.not_to raise_error
+ expect { resource.recursive "monkey" }.to raise_error(ArgumentError)
end
describe "when it has group, mode, and owner" do
before do
- @resource.path("/tmp/foo/bar/")
- @resource.group("wheel")
- @resource.mode("0664")
- @resource.owner("root")
+ resource.path("/tmp/foo/bar/")
+ resource.group("wheel")
+ resource.mode("0664")
+ resource.owner("root")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:group]).to eq("wheel")
expect(state[:mode]).to eq("0664")
expect(state[:owner]).to eq("root")
end
it "returns the directory path as its identity" do
- expect(@resource.identity).to eq("/tmp/foo/bar/")
+ expect(resource.identity).to eq("/tmp/foo/bar/")
end
end
end
diff --git a/spec/unit/resource/deploy_revision_spec.rb b/spec/unit/resource/dmg_package_spec.rb
index aa12b9595d..d01262fa2d 100644
--- a/spec/unit/resource/deploy_revision_spec.rb
+++ b/spec/unit/resource/dmg_package_spec.rb
@@ -1,6 +1,5 @@
#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2009-2016, Daniel DeLeo
+# Copyright:: Copyright 2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,26 +16,24 @@
#
require "spec_helper"
-require "support/shared/unit/resource/static_provider_resolution"
-describe Chef::Resource::DeployRevision do
+describe Chef::Resource::DmgPackage do
- static_provider_resolution(
- resource: Chef::Resource::DeployRevision,
- provider: Chef::Provider::Deploy::Revision,
- name: :deploy_revision,
- action: :deploy
- )
+ let(:resource) { Chef::Resource::DmgPackage.new("fakey_fakerton") }
-end
+ it "has a resource name of :dmg_package" do
+ expect(resource.resource_name).to eql(:dmg_package)
+ end
-describe Chef::Resource::DeployBranch do
+ it "the app property is the name_property" do
+ expect(resource.app).to eql("fakey_fakerton")
+ end
- static_provider_resolution(
- resource: Chef::Resource::DeployBranch,
- provider: Chef::Provider::Deploy::Revision,
- name: :deploy_branch,
- action: :deploy
- )
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+ it "supports :install action" do
+ expect { resource.action :install }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/dnf_package_spec.rb b/spec/unit/resource/dnf_package_spec.rb
index 0cc673d897..f4262a0396 100644
--- a/spec/unit/resource/dnf_package_spec.rb
+++ b/spec/unit/resource/dnf_package_spec.rb
@@ -31,69 +31,78 @@ describe Chef::Resource::DnfPackage, "initialize" do
end
-describe Chef::Resource::DnfPackage, "arch" do
- before(:each) do
- @resource = Chef::Resource::DnfPackage.new("foo")
+describe Chef::Resource::DnfPackage, "defaults" do
+ let(:resource) { Chef::Resource::DnfPackage.new("foo") }
+
+ it "sets the arch variable to whatever is passed in" do
+ resource.arch("i386")
+ expect(resource.arch).to eql(["i386"])
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should set the arch variable to whatever is passed in" do
- @resource.arch("i386")
- expect(@resource.arch).to eql(["i386"])
+ it "supports :flush_cache, :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :flush_cache }.not_to raise_error
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
end
describe Chef::Resource::DnfPackage, "flush_cache" do
- before(:each) do
- @resource = Chef::Resource::DnfPackage.new("foo")
- end
+ let(:resource) { Chef::Resource::DnfPackage.new("foo") }
- it "should default the flush timing to false" do
- flush_hash = { :before => false, :after => false }
- expect(@resource.flush_cache).to eq(flush_hash)
+ it "defaults the flush timing to false" do
+ flush_hash = { before: false, after: false }
+ expect(resource.flush_cache).to eq(flush_hash)
end
- it "should allow you to set the flush timing with an array" do
+ it "allows you to set the flush timing with an array" do
flush_array = [ :before, :after ]
- flush_hash = { :before => true, :after => true }
- @resource.flush_cache(flush_array)
- expect(@resource.flush_cache).to eq(flush_hash)
+ flush_hash = { before: true, after: true }
+ resource.flush_cache(flush_array)
+ expect(resource.flush_cache).to eq(flush_hash)
end
- it "should allow you to set the flush timing with a hash" do
- flush_hash = { :before => true, :after => true }
- @resource.flush_cache(flush_hash)
- expect(@resource.flush_cache).to eq(flush_hash)
+ it "allows you to set the flush timing with a hash" do
+ flush_hash = { before: true, after: true }
+ resource.flush_cache(flush_hash)
+ expect(resource.flush_cache).to eq(flush_hash)
end
- it "should allow 'true' for flush_cache" do
- @resource.flush_cache(true)
- expect(@resource.flush_cache).to eq({ before: true, after: true })
+ it "allows 'true' for flush_cache" do
+ resource.flush_cache(true)
+ expect(resource.flush_cache).to eq({ before: true, after: true })
end
- it "should allow 'false' for flush_cache" do
- @resource.flush_cache(false)
- expect(@resource.flush_cache).to eq({ before: false, after: false })
+ it "allows 'false' for flush_cache" do
+ resource.flush_cache(false)
+ expect(resource.flush_cache).to eq({ before: false, after: false })
end
- it "should allow ':before' for flush_cache" do
- @resource.flush_cache(:before)
- expect(@resource.flush_cache).to eq({ before: true, after: false })
+ it "allows ':before' for flush_cache" do
+ resource.flush_cache(:before)
+ expect(resource.flush_cache).to eq({ before: true, after: false })
end
- it "should allow ':after' for flush_cache" do
- @resource.flush_cache(:after)
- expect(@resource.flush_cache).to eq({ before: false, after: true })
+ it "allows ':after' for flush_cache" do
+ resource.flush_cache(:after)
+ expect(resource.flush_cache).to eq({ before: false, after: true })
end
end
describe Chef::Resource::DnfPackage, "allow_downgrade" do
- before(:each) do
- @resource = Chef::Resource::DnfPackage.new("foo")
- end
+ let(:resource) { Chef::Resource::DnfPackage.new("foo") }
- it "should allow you to specify whether allow_downgrade is true or false" do
+ it "allows you to specify whether allow_downgrade is true or false" do
Chef::Config[:treat_deprecation_warnings_as_errors] = false
- expect { @resource.allow_downgrade true }.not_to raise_error
- expect { @resource.allow_downgrade false }.not_to raise_error
+ expect { resource.allow_downgrade true }.not_to raise_error
+ expect { resource.allow_downgrade false }.not_to raise_error
end
end
diff --git a/spec/unit/resource/dpkg_package_spec.rb b/spec/unit/resource/dpkg_package_spec.rb
index 66ad86b861..ff32d7e413 100644
--- a/spec/unit/resource/dpkg_package_spec.rb
+++ b/spec/unit/resource/dpkg_package_spec.rb
@@ -29,4 +29,22 @@ describe Chef::Resource::DpkgPackage, "initialize" do
os: "linux"
)
+ describe Chef::Resource::DpkgPackage, "defaults" do
+ let(:resource) { Chef::Resource::DpkgPackage.new("fakey_fakerton") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+ end
+
end
diff --git a/spec/unit/resource/dsc_resource_spec.rb b/spec/unit/resource/dsc_resource_spec.rb
index b687811392..22c42aa441 100644
--- a/spec/unit/resource/dsc_resource_spec.rb
+++ b/spec/unit/resource/dsc_resource_spec.rb
@@ -40,31 +40,31 @@ describe Chef::Resource::DscResource do
expect(dsc_test_resource.action).to eq([:run])
end
- it "has an ed_actions attribute with only the `:run` and `:nothing` attributes" do
+ it "has an ed_actions property with only the `:run` and `:nothing` properties" do
expect(dsc_test_resource.allowed_actions.to_set).to eq([:run, :nothing].to_set)
end
- it "allows the resource attribute to be set" do
+ it "allows the resource property to be set" do
dsc_test_resource.resource(dsc_test_resource_name)
expect(dsc_test_resource.resource).to eq(dsc_test_resource_name)
end
- it "allows the module_name attribute to be set" do
+ it "allows the module_name property to be set" do
dsc_test_resource.module_name(dsc_test_resource_name)
expect(dsc_test_resource.module_name).to eq(dsc_test_resource_name)
end
- it "allows the module_version attribute to be set" do
+ it "allows the module_version property to be set" do
dsc_test_resource.module_version(dsc_test_resource_module_version)
expect(dsc_test_resource.module_version).to eq(dsc_test_resource_module_version)
end
- it "allows the reboot_action attribute to be set" do
+ it "allows the reboot_action property to be set" do
dsc_test_resource.reboot_action(dsc_test_reboot_action)
expect(dsc_test_resource.reboot_action).to eq(dsc_test_reboot_action)
end
- it "allows the timeout attribute to be set" do
+ it "allows the timeout property to be set" do
dsc_test_resource.timeout(dsc_test_timeout)
expect(dsc_test_resource.timeout).to eq(dsc_test_timeout)
end
diff --git a/spec/unit/resource/dsc_script_spec.rb b/spec/unit/resource/dsc_script_spec.rb
index f0c81e43b5..26a1c7cca0 100644
--- a/spec/unit/resource/dsc_script_spec.rb
+++ b/spec/unit/resource/dsc_script_spec.rb
@@ -19,7 +19,7 @@
require "spec_helper"
describe Chef::Resource::DscScript do
- let(:dsc_test_resource_name) { "DSCTest" }
+ let(:resource_name) { "DSCTest" }
context "when Powershell supports Dsc" do
let(:dsc_test_run_context) do
@@ -28,8 +28,8 @@ describe Chef::Resource::DscScript do
empty_events = Chef::EventDispatch::Dispatcher.new
Chef::RunContext.new(node, {}, empty_events)
end
- let(:dsc_test_resource) do
- Chef::Resource::DscScript.new(dsc_test_resource_name, dsc_test_run_context)
+ let(:resource) do
+ Chef::Resource::DscScript.new(resource_name, dsc_test_run_context)
end
let(:configuration_code) { 'echo "This is supposed to create a configuration document."' }
let(:configuration_path) { "c:/myconfigs/formatc.ps1" }
@@ -37,41 +37,41 @@ describe Chef::Resource::DscScript do
let(:configuration_data) { '@{AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword = $true })}' }
let(:configuration_data_script) { "c:/myconfigs/data/safedata.psd1" }
- it "has a default action of `:run`" do
- expect(dsc_test_resource.action).to eq([:run])
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
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)
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
end
- it "allows the code attribute to be set" do
- dsc_test_resource.code(configuration_code)
- expect(dsc_test_resource.code).to eq(configuration_code)
+ it "allows the code property to be set" do
+ resource.code(configuration_code)
+ expect(resource.code).to eq(configuration_code)
end
- it "allows the command attribute to be set" do
- dsc_test_resource.command(configuration_path)
- expect(dsc_test_resource.command).to eq(configuration_path)
+ it "allows the command property to be set" do
+ resource.command(configuration_path)
+ expect(resource.command).to eq(configuration_path)
end
- it "allows the configuration_name attribute to be set" do
- dsc_test_resource.configuration_name(configuration_name)
- expect(dsc_test_resource.configuration_name).to eq(configuration_name)
+ it "allows the configuration_name property to be set" do
+ resource.configuration_name(configuration_name)
+ expect(resource.configuration_name).to eq(configuration_name)
end
- it "allows the configuration_data attribute to be set" do
- dsc_test_resource.configuration_data(configuration_data)
- expect(dsc_test_resource.configuration_data).to eq(configuration_data)
+ it "allows the configuration_data property to be set" do
+ resource.configuration_data(configuration_data)
+ expect(resource.configuration_data).to eq(configuration_data)
end
- it "allows the configuration_data_script attribute to be set" do
- dsc_test_resource.configuration_data_script(configuration_data_script)
- expect(dsc_test_resource.configuration_data_script).to eq(configuration_data_script)
+ it "allows the configuration_data_script property to be set" do
+ resource.configuration_data_script(configuration_data_script)
+ expect(resource.configuration_data_script).to eq(configuration_data_script)
end
it "has the ps_credential helper method" do
- expect(dsc_test_resource).to respond_to(:ps_credential)
+ expect(resource).to respond_to(:ps_credential)
end
context "when calling imports" do
@@ -80,55 +80,55 @@ describe Chef::Resource::DscScript do
let(:dsc_resources) { %w{ResourceA ResourceB} }
it "allows an arbitrary number of resources to be set for a module to be set" do
- dsc_test_resource.imports module_name, *dsc_resources
- module_imports = dsc_test_resource.imports[module_name]
+ resource.imports module_name, *dsc_resources
+ module_imports = resource.imports[module_name]
expect(module_imports).to eq(dsc_resources)
end
it "adds * to the imports when no resources are set for a moudle" do
- dsc_test_resource.imports module_name
- module_imports = dsc_test_resource.imports[module_name]
+ resource.imports module_name
+ module_imports = resource.imports[module_name]
expect(module_imports).to eq(["*"])
end
it "allows an arbitrary number of modules" do
- dsc_test_resource.imports module_name
- dsc_test_resource.imports module_name_b
- expect(dsc_test_resource.imports).to have_key(module_name)
- expect(dsc_test_resource.imports).to have_key(module_name_b)
+ resource.imports module_name
+ resource.imports module_name_b
+ expect(resource.imports).to have_key(module_name)
+ expect(resource.imports).to have_key(module_name_b)
end
it "allows resources to be added for a module" do
- dsc_test_resource.imports module_name, dsc_resources[0]
- dsc_test_resource.imports module_name, dsc_resources[1]
- module_imports = dsc_test_resource.imports[module_name]
+ resource.imports module_name, dsc_resources[0]
+ resource.imports module_name, dsc_resources[1]
+ module_imports = resource.imports[module_name]
expect(module_imports).to eq(dsc_resources)
end
end
- it "raises an ArgumentError exception if an attempt is made to set the code attribute when the command attribute is already set" do
- dsc_test_resource.command(configuration_path)
- expect { dsc_test_resource.code(configuration_code) }.to raise_error(ArgumentError)
+ it "raises an ArgumentError exception if an attempt is made to set the code property when the command property is already set" do
+ resource.command(configuration_path)
+ expect { resource.code(configuration_code) }.to raise_error(ArgumentError)
end
- it "raises an ArgumentError exception if an attempt is made to set the command attribute when the code attribute is already set" do
- dsc_test_resource.code(configuration_code)
- expect { dsc_test_resource.command(configuration_path) }.to raise_error(ArgumentError)
+ it "raises an ArgumentError exception if an attempt is made to set the command property when the code property is already set" do
+ resource.code(configuration_code)
+ expect { resource.command(configuration_path) }.to raise_error(ArgumentError)
end
- it "raises an ArgumentError exception if an attempt is made to set the configuration_name attribute when the code attribute is already set" do
- dsc_test_resource.code(configuration_code)
- expect { dsc_test_resource.configuration_name(configuration_name) }.to raise_error(ArgumentError)
+ it "raises an ArgumentError exception if an attempt is made to set the configuration_name property when the code property is already set" do
+ resource.code(configuration_code)
+ expect { resource.configuration_name(configuration_name) }.to raise_error(ArgumentError)
end
- it "raises an ArgumentError exception if an attempt is made to set the configuration_data attribute when the configuration_data_script attribute is already set" do
- dsc_test_resource.configuration_data_script(configuration_data_script)
- expect { dsc_test_resource.configuration_data(configuration_data) }.to raise_error(ArgumentError)
+ it "raises an ArgumentError exception if an attempt is made to set the configuration_data property when the configuration_data_script property is already set" do
+ resource.configuration_data_script(configuration_data_script)
+ expect { resource.configuration_data(configuration_data) }.to raise_error(ArgumentError)
end
- it "raises an ArgumentError exception if an attempt is made to set the configuration_data_script attribute when the configuration_data attribute is already set" do
- dsc_test_resource.configuration_data(configuration_data)
- expect { dsc_test_resource.configuration_data_script(configuration_data_script) }.to raise_error(ArgumentError)
+ it "raises an ArgumentError exception if an attempt is made to set the configuration_data_script property when the configuration_data property is already set" do
+ resource.configuration_data(configuration_data)
+ expect { resource.configuration_data_script(configuration_data_script) }.to raise_error(ArgumentError)
end
end
end
diff --git a/spec/unit/resource/env_spec.rb b/spec/unit/resource/env_spec.rb
deleted file mode 100644
index 1c63ab519f..0000000000
--- a/spec/unit/resource/env_spec.rb
+++ /dev/null
@@ -1,85 +0,0 @@
-#
-# Author:: Doug MacEachern (<dougm@vmware.com>)
-# Author:: Tyler Cloke (<tyler@chef.io>)
-# Copyright:: Copyright 2010-2016, VMware, Inc.
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Resource::Env do
-
- before(:each) do
- @resource = Chef::Resource::Env.new("FOO")
- end
-
- it "should create a new Chef::Resource::Env" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Env)
- end
-
- it "should have a name" do
- expect(@resource.name).to eql("FOO")
- end
-
- it "should have a default action of 'create'" do
- expect(@resource.action).to eql([:create])
- end
-
- { :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)
- else
- expect { @resource.action action }.not_to raise_error
- end
- end
- end
-
- it "should use the object name as the key_name by default" do
- expect(@resource.key_name).to eql("FOO")
- end
-
- it "should accept a string as the env value via 'value'" do
- expect { @resource.value "bar" }.not_to raise_error
- end
-
- it "should not accept a Hash for the env value via 'to'" do
- expect { @resource.value Hash.new }.to raise_error(ArgumentError)
- end
-
- it "should allow you to set an env value via 'to'" do
- @resource.value "bar"
- expect(@resource.value).to eql("bar")
- end
-
- describe "when it has key name and value" do
- before do
- @resource.key_name("charmander")
- @resource.value("level7")
- @resource.delim("hi")
- end
-
- it "describes its state" do
- state = @resource.state_for_resource_reporter
- expect(state[:value]).to eq("level7")
- end
-
- it "returns the key name as its identity" 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
deleted file mode 100644
index 6d1f45ec63..0000000000
--- a/spec/unit/resource/erl_call_spec.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-#
-# Author:: Joe Williams (<joe@joetify.com>)
-# Author:: Tyler Cloke (<tyler@chef.io>)
-# Copyright:: Copyright 2009-2016, Joe Williams
-# License:: Apache License, Version 2.0
-#
-# 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.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-require "spec_helper"
-
-describe Chef::Resource::ErlCall do
-
- before(:each) do
- @resource = Chef::Resource::ErlCall.new("fakey_fakerton")
- end
-
- it "should create a new Chef::Resource::ErlCall" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::ErlCall)
- end
-
- it "should have a resource name of :erl_call" do
- expect(@resource.resource_name).to eql(:erl_call)
- end
-
- it "should have a default action of run" do
- expect(@resource.action).to eql([:run])
- end
-
- it "should accept run as an action" do
- expect { @resource.action :run }.not_to raise_error
- end
-
- it "should allow you to set the code attribute" do
- @resource.code "q()."
- expect(@resource.code).to eql("q().")
- end
-
- it "should allow you to set the cookie attribute" do
- @resource.cookie "nomnomnom"
- expect(@resource.cookie).to eql("nomnomnom")
- end
-
- it "should allow you to set the distributed attribute" do
- @resource.distributed true
- expect(@resource.distributed).to eql(true)
- end
-
- it "should allow you to set the name_type attribute" do
- @resource.name_type "sname"
- expect(@resource.name_type).to eql("sname")
- end
-
- it "should allow you to set the node_name attribute" do
- @resource.node_name "chef@erlang"
- expect(@resource.node_name).to eql("chef@erlang")
- end
-
- describe "when it has cookie and node_name" do
- before do
- @resource.code("erl-call:function()")
- @resource.cookie("cookie")
- @resource.node_name("raster")
- end
-
- it "returns the code as its identity" do
- expect(@resource.identity).to eq("erl-call:function()")
- end
- end
-end
diff --git a/spec/unit/resource/execute_spec.rb b/spec/unit/resource/execute_spec.rb
index 575c80ba2f..9bd434b74a 100644
--- a/spec/unit/resource/execute_spec.rb
+++ b/spec/unit/resource/execute_spec.rb
@@ -21,15 +21,23 @@ require "spec_helper"
describe Chef::Resource::Execute do
let(:resource_instance_name) { "some command" }
- let(:execute_resource) { Chef::Resource::Execute.new(resource_instance_name) }
+ let(:resource) { Chef::Resource::Execute.new(resource_instance_name) }
it_behaves_like "an execute resource"
- it "default guard interpreter should be :execute interpreter" do
- expect(execute_resource.guard_interpreter).to be(:execute)
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
+ end
+
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
+ end
+
+ it "default guard interpreter is :execute interpreter" do
+ expect(resource.guard_interpreter).to be(:execute)
end
it "defaults to not being a guard interpreter" do
- expect(execute_resource.is_guard_interpreter).to eq(false)
+ expect(resource.is_guard_interpreter).to eq(false)
end
describe "#qualify_user" do
@@ -40,7 +48,7 @@ describe Chef::Resource::Execute do
let(:username) { "user@domain" }
it "correctly parses the user and domain" do
- identity = execute_resource.qualify_user(username, password, domain)
+ identity = resource.qualify_user(username, password, domain)
expect(identity[:domain]).to eq("domain")
expect(identity[:user]).to eq("user")
end
@@ -50,7 +58,7 @@ describe Chef::Resource::Execute do
let(:username) { "domain\\user" }
it "correctly parses the user and domain" do
- identity = execute_resource.qualify_user(username, password, domain)
+ identity = resource.qualify_user(username, password, domain)
expect(identity[:domain]).to eq("domain")
expect(identity[:user]).to eq("user")
end
@@ -59,15 +67,15 @@ describe Chef::Resource::Execute do
shared_examples_for "it received valid credentials" do
describe "the validation method" do
- it "should not raise an error" do
- expect { execute_resource.validate_identity_platform(username, password, domain) }.not_to raise_error
+ it "does not raise an error" do
+ expect { resource.validate_identity_platform(username, password, domain) }.not_to raise_error
end
end
describe "the name qualification method" do
- it "should correctly translate the user and domain" do
+ it "correctly translates the user and domain" do
identity = nil
- expect { identity = execute_resource.qualify_user(username, password, domain) }.not_to raise_error
+ expect { identity = resource.qualify_user(username, password, domain) }.not_to raise_error
expect(identity[:domain]).to eq(domain)
expect(identity[:user]).to eq(username)
end
@@ -76,24 +84,24 @@ describe Chef::Resource::Execute do
shared_examples_for "it received invalid credentials" do
describe "the validation method" do
- it "should raise an error" do
- expect { execute_resource.validate_identity_platform(username, password, domain, elevated) }.to raise_error(ArgumentError)
+ it "raises an error" do
+ expect { resource.validate_identity_platform(username, password, domain, elevated) }.to raise_error(ArgumentError)
end
end
end
shared_examples_for "it received invalid username and domain" do
describe "the validation method" do
- it "should raise an error" do
- expect { execute_resource.qualify_user(username, password, domain) }.to raise_error(ArgumentError)
+ it "raises an error" do
+ expect { resource.qualify_user(username, password, domain) }.to raise_error(ArgumentError)
end
end
end
shared_examples_for "it received credentials that are not valid on the platform" do
describe "the validation method" do
- it "should raise an error" do
- expect { execute_resource.validate_identity_platform(username, password, domain) }.to raise_error(Chef::Exceptions::UnsupportedPlatform)
+ it "raises an error" do
+ expect { resource.validate_identity_platform(username, password, domain) }.to raise_error(Chef::Exceptions::UnsupportedPlatform)
end
end
end
@@ -101,7 +109,7 @@ describe Chef::Resource::Execute do
shared_examples_for "a consumer of the Execute resource" do
context "when running on Windows" do
before do
- allow(execute_resource).to receive(:node).and_return({ :platform_family => "windows" })
+ allow(resource).to receive(:node).and_return({ platform_family: "windows" })
end
context "when no user, domain, or password is specified" do
@@ -203,7 +211,7 @@ describe Chef::Resource::Execute do
context "when not running on Windows" do
before do
- allow(execute_resource).to receive(:node).and_return({ :platform_family => "ubuntu" })
+ allow(resource).to receive(:node).and_return({ platform_family: "ubuntu" })
end
context "when no user, domain, or password is specified" do
diff --git a/spec/unit/resource/file/verification/systemd_unit_spec.rb b/spec/unit/resource/file/verification/systemd_unit_spec.rb
index 8a3d849582..b1f9239442 100644
--- a/spec/unit/resource/file/verification/systemd_unit_spec.rb
+++ b/spec/unit/resource/file/verification/systemd_unit_spec.rb
@@ -20,7 +20,7 @@ require "spec_helper"
describe Chef::Resource::File::Verification::SystemdUnit do
let(:command) { "#{systemd_analyze_path} verify %{path}" }
- let(:opts) { { :future => true } }
+ let(:opts) { { future: true } }
let(:parent_resource) { Chef::Resource.new("llama") }
let(:systemd_analyze_path) { "/usr/bin/systemd-analyze" }
let(:systemd_dir) { "/etc/systemd/system" }
diff --git a/spec/unit/resource/file/verification_spec.rb b/spec/unit/resource/file/verification_spec.rb
index feacd715a4..f0ec999019 100644
--- a/spec/unit/resource/file/verification_spec.rb
+++ b/spec/unit/resource/file/verification_spec.rb
@@ -48,7 +48,7 @@ describe Chef::Resource::File::Verification do
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
@@ -66,6 +66,11 @@ describe Chef::Resource::File::Verification do
v = Chef::Resource::File::Verification.new(parent_resource, nil, {}, &f_block)
expect(v.verify(temp_path)).to eq(false)
end
+
+ it "responds to to_s" do
+ v = Chef::Resource::File::Verification.new(parent_resource, nil, {}) {}
+ expect(v.to_s).to eq("<Proc>")
+ end
end
context "with a verification command(String)" do
@@ -110,23 +115,32 @@ describe Chef::Resource::File::Verification do
v = Chef::Resource::File::Verification.new(parent_resource, "true", {})
expect(v.verify(temp_path)).to eq(true)
end
+
+ it "responds to to_s" do
+ v = Chef::Resource::File::Verification.new(parent_resource, "some command --here", {})
+ expect(v.to_s).to eq("some command --here")
+ end
end
context "with a named verification(Symbol)" do
+ let(:registered_verification) { double("registered_verification") }
+ subject { described_class.new(parent_resource, :cats, {}) }
before(:each) do
class Chef::Resource::File::Verification::Turtle < Chef::Resource::File::Verification
provides :cats
def verify(path, opts)
end
end
+ allow(Chef::Resource::File::Verification::Turtle).to receive(:new).and_return(registered_verification)
end
it "delegates to the registered verification" do
- registered_verification = double()
- allow(Chef::Resource::File::Verification::Turtle).to receive(:new).and_return(registered_verification)
- v = Chef::Resource::File::Verification.new(parent_resource, :cats, {})
expect(registered_verification).to receive(:verify).with(temp_path, {})
- v.verify(temp_path, {})
+ subject.verify(temp_path, {})
+ end
+
+ it "responds to to_s" do
+ expect(subject.to_s).to eq(":cats (Chef::Resource::File::Verification::Turtle)")
end
end
end
diff --git a/spec/unit/resource/file_spec.rb b/spec/unit/resource/file_spec.rb
index 4004798dad..5e649da1a9 100644
--- a/spec/unit/resource/file_spec.rb
+++ b/spec/unit/resource/file_spec.rb
@@ -20,88 +20,86 @@ require "spec_helper"
describe Chef::Resource::File do
- before(:each) do
- @resource = Chef::Resource::File.new("fakey_fakerton")
- end
+ let(:resource) { Chef::Resource::File.new("fakey_fakerton") }
- it "should have a name" do
- expect(@resource.name).to eql("fakey_fakerton")
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
end
- it "should have a default action of 'create'" do
- expect(@resource.action).to eql([:create])
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should have a default content of nil" do
- expect(@resource.content).to be_nil
+ it "supports :create, :create_if_missing, :delete, :touch actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :touch }.not_to raise_error
end
- it "should be set to back up 5 files by default" do
- expect(@resource.backup).to eql(5)
+ it "has a default content of nil" do
+ expect(resource.content).to be_nil
end
- it "should only accept strings for content" do
- expect { @resource.content 5 }.to raise_error(ArgumentError)
- expect { @resource.content :foo }.to raise_error(ArgumentError)
- expect { @resource.content "hello" => "there" }.to raise_error(ArgumentError)
- expect { @resource.content "hi" }.not_to raise_error
+ it "is set to back up 5 files by default" do
+ expect(resource.backup).to eql(5)
end
- it "should only accept false or a number for backup" do
- expect { @resource.backup true }.to raise_error(ArgumentError)
- expect { @resource.backup false }.not_to raise_error
- expect { @resource.backup 10 }.not_to raise_error
- expect { @resource.backup "blues" }.to raise_error(ArgumentError)
+ it "only accept strings for content" do
+ expect { resource.content 5 }.to raise_error(ArgumentError)
+ expect { resource.content :foo }.to raise_error(ArgumentError)
+ expect { resource.content "hello" => "there" }.to raise_error(ArgumentError)
+ expect { resource.content "hi" }.not_to raise_error
end
- it "should accept a sha256 for checksum" do
- expect { @resource.checksum "0fd012fdc96e96f8f7cf2046522a54aed0ce470224513e45da6bc1a17a4924aa" }.not_to raise_error
- expect { @resource.checksum "monkey!" }.to raise_error(ArgumentError)
+ it "only accept false or a number for backup" do
+ expect { resource.backup true }.to raise_error(ArgumentError)
+ expect { resource.backup false }.not_to raise_error
+ expect { resource.backup 10 }.not_to raise_error
+ expect { resource.backup "blues" }.to raise_error(ArgumentError)
end
- it "should accept create, delete or touch for action" do
- expect { @resource.action :create }.not_to raise_error
- expect { @resource.action :delete }.not_to raise_error
- expect { @resource.action :touch }.not_to raise_error
- expect { @resource.action :blues }.to raise_error(ArgumentError)
+ it "accepts a sha256 for checksum" do
+ expect { resource.checksum "0fd012fdc96e96f8f7cf2046522a54aed0ce470224513e45da6bc1a17a4924aa" }.not_to raise_error
+ expect { resource.checksum "monkey!" }.to raise_error(ArgumentError)
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(ArgumentError)
- expect { @resource.verify false }.to raise_error(ArgumentError)
+ it "accepts 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(ArgumentError)
+ expect { resource.verify false }.to raise_error(ArgumentError)
end
- it "should accept multiple verify statements" do
- @resource.verify "foo"
- @resource.verify "bar"
- @resource.verify.length == 2
+ it "accepts multiple verify statements" do
+ resource.verify "foo"
+ resource.verify "bar"
+ resource.verify.length == 2
end
- it "should use the object name as the path by default" do
- expect(@resource.path).to eql("fakey_fakerton")
+ it "uses the object name as the path by default" do
+ expect(resource.path).to eql("fakey_fakerton")
end
- it "should accept a string as the path" do
- expect { @resource.path "/tmp" }.not_to raise_error
- expect(@resource.path).to eql("/tmp")
- expect { @resource.path Hash.new }.to raise_error(ArgumentError)
+ it "accepts a string as the path" do
+ expect { resource.path "/tmp" }.not_to raise_error
+ expect(resource.path).to eql("/tmp")
+ expect { resource.path Hash.new }.to raise_error(ArgumentError)
end
describe "when it has a path, owner, group, mode, and checksum" do
before do
- @resource.path("/tmp/foo.txt")
- @resource.owner("root")
- @resource.group("wheel")
- @resource.mode("0644")
- @resource.checksum("1" * 64)
+ resource.path("/tmp/foo.txt")
+ resource.owner("root")
+ resource.group("wheel")
+ resource.mode("0644")
+ resource.checksum("1" * 64)
end
context "on unix", :unix_only do
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:owner]).to eq("root")
expect(state[:group]).to eq("wheel")
expect(state[:mode]).to eq("0644")
@@ -110,21 +108,20 @@ describe Chef::Resource::File do
end
it "returns the file path as its identity" do
- expect(@resource.identity).to eq("/tmp/foo.txt")
+ expect(resource.identity).to eq("/tmp/foo.txt")
end
end
- describe "when access controls are set on windows", :windows_only => true do
+ describe "when access controls are set on windows", windows_only: true do
before do
- @resource.rights :read, "Everyone"
- @resource.rights :full_control, "DOMAIN\User"
+ resource.rights :read, "Everyone"
+ resource.rights :full_control, "DOMAIN\User"
end
it "describes its state including windows ACL attributes" do
- state = @resource.state_for_resource_reporter
- expect(state[:rights]).to eq([ { :permissions => :read, :principals => "Everyone" },
- { :permissions => :full_control, :principals => "DOMAIN\User" } ])
+ state = resource.state_for_resource_reporter
+ 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 ce4300497e..154bd09616 100644
--- a/spec/unit/resource/freebsd_package_spec.rb
+++ b/spec/unit/resource/freebsd_package_spec.rb
@@ -22,64 +22,80 @@ require "spec_helper"
require "ostruct"
describe Chef::Resource::FreebsdPackage do
- before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @resource = Chef::Resource::FreebsdPackage.new("foo", @run_context)
- end
+ let(:node) { Chef::Node.new }
+ let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:run_context) { Chef::RunContext.new(node, {}, events) }
+ let(:resource) { Chef::Resource::FreebsdPackage.new("foo", run_context) }
describe "Initialization" do
- it "should return a Chef::Resource::FreebsdPackage" do
- expect(@resource).to be_a_kind_of(Chef::Resource::FreebsdPackage)
+
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
+ end
+
+ it "sets the resource_name to :freebsd_package" do
+ expect(resource.resource_name).to eql(:freebsd_package)
end
- it "should set the resource_name to :freebsd_package" do
- expect(@resource.resource_name).to eql(:freebsd_package)
+ it "does not set the provider" do
+ expect(resource.provider).to be_nil
+ end
+ end
+
+ describe "Actions" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should not set the provider" do
- expect(@resource.provider).to be_nil
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
end
describe "Assigning provider after creation" do
describe "if ports specified as source" do
- it "should be Freebsd::Port" do
- @resource.source("ports")
- @resource.after_created
- expect(@resource.provider).to eq(Chef::Provider::Package::Freebsd::Port)
+ it "is Freebsd::Port" do
+ resource.source("ports")
+ resource.after_created
+ expect(resource.provider).to eq(Chef::Provider::Package::Freebsd::Port)
end
end
describe "if freebsd_version is greater than or equal to 1000017" do
- it "should be Freebsd::Pkgng" do
+ it "is Freebsd::Pkgng" do
[1000017, 1000018, 1000500, 1001001, 1100000].each do |freebsd_version|
- @node.automatic_attrs[:os_version] = freebsd_version
- @resource.after_created
- expect(@resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkgng)
+ node.automatic_attrs[:os_version] = freebsd_version
+ resource.after_created
+ expect(resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkgng)
end
end
end
describe "if pkgng enabled" do
- it "should be Freebsd::Pkgng" do
- pkg_enabled = OpenStruct.new(:stdout => "yes\n")
- allow(@resource).to receive(:shell_out!).with("make", "-V", "WITH_PKGNG", :env => nil).and_return(pkg_enabled)
- @resource.after_created
- expect(@resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkgng)
+ it "is Freebsd::Pkgng" do
+ pkg_enabled = OpenStruct.new(stdout: "yes\n")
+ allow(resource).to receive(:shell_out!).with("make", "-V", "WITH_PKGNG", env: nil).and_return(pkg_enabled)
+ resource.after_created
+ expect(resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkgng)
end
end
describe "if freebsd_version is less than 1000017 and pkgng not enabled" do
- it "should be Freebsd::Pkg" do
- pkg_enabled = OpenStruct.new(:stdout => "\n")
- allow(@resource).to receive(:shell_out!).with("make", "-V", "WITH_PKGNG", :env => nil).and_return(pkg_enabled)
+ it "is Freebsd::Pkg" do
+ pkg_enabled = OpenStruct.new(stdout: "\n")
+ allow(resource).to receive(:shell_out!).with("make", "-V", "WITH_PKGNG", env: nil).and_return(pkg_enabled)
[1000016, 1000000, 901503, 902506, 802511].each do |freebsd_version|
- @node.automatic_attrs[:os_version] = freebsd_version
- @resource.after_created
- expect(@resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkg)
+ node.automatic_attrs[:os_version] = freebsd_version
+ expect(Chef).to receive(:deprecated).with(:freebsd_package_provider, kind_of(String))
+ resource.after_created
+ expect(resource.provider).to eq(Chef::Provider::Package::Freebsd::Pkg)
end
end
end
diff --git a/spec/unit/resource/gem_package_spec.rb b/spec/unit/resource/gem_package_spec.rb
index a1571ab9bb..aba6ab1032 100644
--- a/spec/unit/resource/gem_package_spec.rb
+++ b/spec/unit/resource/gem_package_spec.rb
@@ -31,12 +31,37 @@ describe Chef::Resource::GemPackage, "initialize" do
end
describe Chef::Resource::GemPackage, "gem_binary" do
- before(:each) do
- @resource = Chef::Resource::GemPackage.new("foo")
+ let(:resource) { Chef::Resource::GemPackage.new("foo") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "sets the gem_binary variable to whatever is passed in" do
+ resource.gem_binary("/opt/local/bin/gem")
+ expect(resource.gem_binary).to eql("/opt/local/bin/gem")
+ end
+end
+
+describe Chef::Resource::GemPackage, "clear_gem_sources" do
+ let(:resource) { Chef::Resource::GemPackage.new("foo") }
+
+ it "is false by default" do
+ expect(resource.clear_sources).to be false
end
- it "should set the gem_binary variable to whatever is passed in" do
- @resource.gem_binary("/opt/local/bin/gem")
- expect(@resource.gem_binary).to eql("/opt/local/bin/gem")
+ it "sets the default of clear_sources to the config value" do
+ Chef::Config[:clear_gem_sources] = true
+ expect(resource.clear_sources).to be true
end
end
diff --git a/spec/unit/resource/git_spec.rb b/spec/unit/resource/git_spec.rb
index 15c1e54f25..660cfcf5ae 100644
--- a/spec/unit/resource/git_spec.rb
+++ b/spec/unit/resource/git_spec.rb
@@ -17,7 +17,6 @@
#
require "spec_helper"
-require "support/shared/unit/resource/static_provider_resolution"
describe Chef::Resource::Git do
@@ -28,23 +27,36 @@ describe Chef::Resource::Git do
action: :sync
)
- before(:each) do
- @git = Chef::Resource::Git.new("my awesome webapp")
- end
+ let(:resource) { Chef::Resource::Git.new("fakey_fakerton") }
- it "is a kind of Scm Resource" do
- expect(@git).to be_a_kind_of(Chef::Resource::Scm)
- expect(@git).to be_an_instance_of(Chef::Resource::Git)
+ it "is a subclass of Chef::Resource::Scm" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Scm)
end
it "uses aliases revision as branch" do
- @git.branch "HEAD"
- expect(@git.revision).to eql("HEAD")
+ resource.branch "HEAD"
+ expect(resource.revision).to eql("HEAD")
end
it "aliases revision as reference" do
- @git.reference "v1.0 tag"
- expect(@git.revision).to eql("v1.0 tag")
+ resource.reference "v1.0 tag"
+ expect(resource.revision).to eql("v1.0 tag")
+ end
+
+ it "the destination property is the name_property" do
+ expect(resource.destination).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :sync" do
+ expect(resource.action).to eql([:sync])
+ end
+
+ it "supports :checkout, :diff, :export, :log, :sync actions" do
+ expect { resource.action :checkout }.not_to raise_error
+ expect { resource.action :diff }.not_to raise_error
+ expect { resource.action :export }.not_to raise_error
+ expect { resource.action :log }.not_to raise_error
+ expect { resource.action :sync }.not_to raise_error
end
end
diff --git a/spec/unit/resource/group_spec.rb b/spec/unit/resource/group_spec.rb
index 8772f37a2b..10bef38410 100644
--- a/spec/unit/resource/group_spec.rb
+++ b/spec/unit/resource/group_spec.rb
@@ -20,143 +20,129 @@
require "spec_helper"
describe Chef::Resource::Group, "initialize" do
- before(:each) do
- @resource = Chef::Resource::Group.new("admin")
- end
-
- it "should create a new Chef::Resource::Group" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Group)
- end
+ let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
- it "should set the resource_name to :group" do
- expect(@resource.resource_name).to eql(:group)
+ it "sets the resource_name to :group" do
+ expect(resource.resource_name).to eql(:group)
end
- it "should set the group_name equal to the argument to initialize" do
- expect(@resource.group_name).to eql("admin")
+ it "the group_name property is the name_property" do
+ expect(resource.group_name).to eql("fakey_fakerton")
end
- it "should default gid to nil" do
- expect(@resource.gid).to eql(nil)
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should default members to an empty array" do
- expect(@resource.members).to eql([])
+ it "supports :create, :manage, :modify, :remove actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :manage }.not_to raise_error
+ expect { resource.action :modify }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
end
- it "should alias users to members, also an empty array" do
- expect(@resource.users).to eql([])
+ it "defaults gid to nil" do
+ expect(resource.gid).to eql(nil)
end
- it "should set action to :create" do
- expect(@resource.action).to eql([:create])
+ it "defaults members to an empty array" do
+ expect(resource.members).to eql([])
end
- %w{create remove modify manage}.each do |action|
- it "should allow action #{action}" do
- expect(@resource.allowed_actions.detect { |a| a == action.to_sym }).to eql(action.to_sym)
- end
+ it "aliases users to members, also an empty array" do
+ expect(resource.users).to eql([])
end
- it "should accept domain groups (@ or \ separator) on non-windows" do
- expect { @resource.group_name "domain\@group" }.not_to raise_error
- expect(@resource.group_name).to eq("domain\@group")
- expect { @resource.group_name "domain\\group" }.not_to raise_error
- expect(@resource.group_name).to eq("domain\\group")
- expect { @resource.group_name "domain\\group^name" }.not_to raise_error
- expect(@resource.group_name).to eq("domain\\group^name")
+ it "accepts domain groups (@ or \ separator) on non-windows" do
+ expect { resource.group_name "domain\@group" }.not_to raise_error
+ expect(resource.group_name).to eq("domain\@group")
+ expect { resource.group_name "domain\\group" }.not_to raise_error
+ expect(resource.group_name).to eq("domain\\group")
+ expect { resource.group_name "domain\\group^name" }.not_to raise_error
+ expect(resource.group_name).to eq("domain\\group^name")
end
end
describe Chef::Resource::Group, "group_name" do
- before(:each) do
- @resource = Chef::Resource::Group.new("admin")
- end
+ let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
- it "should allow a string" do
- @resource.group_name "pirates"
- expect(@resource.group_name).to eql("pirates")
+ it "allows a string" do
+ resource.group_name "pirates"
+ expect(resource.group_name).to eql("pirates")
end
- it "should not allow a hash" do
- expect { @resource.send(:group_name, { :aj => "is freakin awesome" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(:group_name, { aj: "is freakin awesome" }) }.to raise_error(ArgumentError)
end
end
describe Chef::Resource::Group, "gid" do
- before(:each) do
- @resource = Chef::Resource::Group.new("admin")
- end
+ let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
- it "should allow an integer" do
- @resource.gid 100
- expect(@resource.gid).to eql(100)
+ it "allows an integer" do
+ resource.gid 100
+ expect(resource.gid).to eql(100)
end
- it "should not allow a hash" do
- expect { @resource.send(:gid, { :aj => "is freakin awesome" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(:gid, { aj: "is freakin awesome" }) }.to raise_error(ArgumentError)
end
end
describe Chef::Resource::Group, "members" do
- before(:each) do
- @resource = Chef::Resource::Group.new("admin")
- end
+ let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
[ :users, :members].each do |method|
- it "(#{method}) should allow and convert a string" do
- @resource.send(method, "aj")
- expect(@resource.send(method)).to eql(["aj"])
+ it "(#{method}) allows and convert a string" do
+ resource.send(method, "aj")
+ expect(resource.send(method)).to eql(["aj"])
end
it "(#{method}) should split a string on commas" do
- @resource.send(method, "aj,adam")
- expect(@resource.send(method)).to eql( %w{aj adam} )
+ resource.send(method, "aj,adam")
+ expect(resource.send(method)).to eql( %w{aj adam} )
end
- it "(#{method}) should allow an array" do
- @resource.send(method, %w{aj adam})
- expect(@resource.send(method)).to eql( %w{aj adam} )
+ it "(#{method}) allows an array" do
+ resource.send(method, %w{aj adam})
+ expect(resource.send(method)).to eql( %w{aj adam} )
end
- it "(#{method}) should not allow a hash" do
- expect { @resource.send(method, { :aj => "is freakin awesome" }) }.to raise_error(ArgumentError)
+ it "(#{method}) does not allow a hash" do
+ expect { resource.send(method, { aj: "is freakin awesome" }) }.to raise_error(ArgumentError)
end
end
end
describe Chef::Resource::Group, "append" do
- before(:each) do
- @resource = Chef::Resource::Group.new("admin")
- end
+ let(:resource) { Chef::Resource::Group.new("fakey_fakerton") }
- it "should default to false" do
- expect(@resource.append).to eql(false)
+ it "defaults to false" do
+ expect(resource.append).to eql(false)
end
- it "should allow a boolean" do
- @resource.append true
- expect(@resource.append).to eql(true)
+ it "allows a boolean" do
+ resource.append true
+ expect(resource.append).to eql(true)
end
- it "should not allow a hash" do
- expect { @resource.send(:gid, { :aj => "is freakin awesome" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(:gid, { aj: "is freakin awesome" }) }.to raise_error(ArgumentError)
end
describe "when it has members" do
before do
- @resource.group_name("pokemon")
- @resource.members(%w{blastoise pikachu})
+ resource.group_name("pokemon")
+ resource.members(%w{blastoise pikachu})
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:members]).to eql(%w{blastoise pikachu})
end
it "returns the group name as its identity" do
- expect(@resource.identity).to eq("pokemon")
+ expect(resource.identity).to eq("pokemon")
end
end
end
diff --git a/spec/unit/resource/homebrew_cask_spec.rb b/spec/unit/resource/homebrew_cask_spec.rb
new file mode 100644
index 0000000000..a52a552cd9
--- /dev/null
+++ b/spec/unit/resource/homebrew_cask_spec.rb
@@ -0,0 +1,40 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::HomebrewCask do
+
+ let(:resource) { Chef::Resource::HomebrewCask.new("fakey_fakerton") }
+
+ it "has a resource name of :homebrew_cask" do
+ expect(resource.resource_name).to eql(:homebrew_cask)
+ end
+
+ it "the cask_name property is the name_property" do
+ expect(resource.cask_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :remove actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/homebrew_package_spec.rb b/spec/unit/resource/homebrew_package_spec.rb
index cfcfcd9c3a..4c73021a1c 100644
--- a/spec/unit/resource/homebrew_package_spec.rb
+++ b/spec/unit/resource/homebrew_package_spec.rb
@@ -30,6 +30,24 @@ describe Chef::Resource::HomebrewPackage, "initialize" do
let(:resource) { Chef::Resource::HomebrewPackage.new("emacs") }
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
shared_examples "home_brew user set and returned" do
it "returns the configured homebrew_user" do
resource.homebrew_user user
diff --git a/spec/unit/resource/homebrew_tap_spec.rb b/spec/unit/resource/homebrew_tap_spec.rb
new file mode 100644
index 0000000000..0b20b70bdc
--- /dev/null
+++ b/spec/unit/resource/homebrew_tap_spec.rb
@@ -0,0 +1,44 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::HomebrewTap do
+
+ let(:resource) { Chef::Resource::HomebrewTap.new("user/mytap") }
+
+ it "has a resource name of :homebrew_tap" do
+ expect(resource.resource_name).to eql(:homebrew_tap)
+ end
+
+ it "the tap_name property is the name_property" do
+ expect(resource.tap_name).to eql("user/mytap")
+ end
+
+ it "sets the default action as :tap" do
+ expect(resource.action).to eql([:tap])
+ end
+
+ it "supports :tap, :untap actions" do
+ expect { resource.action :tap }.not_to raise_error
+ expect { resource.action :untap }.not_to raise_error
+ end
+
+ it "fails if tap_name isn't in the USER/TAP format" do
+ expect { resource.tap_name "mytap" }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/hostname_spec.rb b/spec/unit/resource/hostname_spec.rb
new file mode 100644
index 0000000000..f0b01d0eb6
--- /dev/null
+++ b/spec/unit/resource/hostname_spec.rb
@@ -0,0 +1,47 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::Hostname do
+
+ let(:resource) { Chef::Resource::Hostname.new("fakey_fakerton") }
+
+ it "has a resource name of :hostname" do
+ expect(resource.resource_name).to eql(:hostname)
+ end
+
+ it "the hostname property is the name_property" do
+ expect(resource.hostname).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :set" do
+ expect(resource.action).to eql([:set])
+ end
+
+ it "supports :set action" do
+ expect { resource.action :set }.not_to raise_error
+ end
+
+ it "runs at compile_time by default" do
+ expect(resource.compile_time).to eql(true)
+ end
+
+ it "reboots windows nodes by default" do
+ expect(resource.windows_reboot).to eql(true)
+ end
+end
diff --git a/spec/unit/resource/http_request_spec.rb b/spec/unit/resource/http_request_spec.rb
index 318a154b88..98cbbd724f 100644
--- a/spec/unit/resource/http_request_spec.rb
+++ b/spec/unit/resource/http_request_spec.rb
@@ -20,39 +20,45 @@
require "spec_helper"
describe Chef::Resource::HttpRequest do
+ let(:resource) { Chef::Resource::HttpRequest.new("fakey_fakerton") }
- before(:each) do
- @resource = Chef::Resource::HttpRequest.new("fakey_fakerton")
+ it "sets the default action as :get" do
+ expect(resource.action).to eql([:get])
end
- it "should create a new Chef::Resource::HttpRequest" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::HttpRequest)
+ it "supports :delete, :get, :head, :options, :patch, :post, :put actions" do
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :get }.not_to raise_error
+ expect { resource.action :head }.not_to raise_error
+ expect { resource.action :options }.not_to raise_error
+ expect { resource.action :patch }.not_to raise_error
+ expect { resource.action :post }.not_to raise_error
+ expect { resource.action :put }.not_to raise_error
end
- it "should set url to a string" do
- @resource.url "http://slashdot.org"
- expect(@resource.url).to eql("http://slashdot.org")
+ it "sets url to a string" do
+ resource.url "http://slashdot.org"
+ expect(resource.url).to eql("http://slashdot.org")
end
- it "should set the message to the name by default" do
- expect(@resource.message).to eql("fakey_fakerton")
+ it "sets the message to the name by default" do
+ expect(resource.message).to eql("fakey_fakerton")
end
- it "should set message to a string" do
- @resource.message "monkeybars"
- expect(@resource.message).to eql("monkeybars")
+ it "sets message to a string" do
+ resource.message "monkeybars"
+ expect(resource.message).to eql("monkeybars")
end
describe "when it has a message and headers" do
before do
- @resource.url("http://www.trololol.net")
- @resource.message("Get sum post brah.")
- @resource.headers({ "head" => "tail" })
+ resource.url("http://www.trololol.net")
+ resource.message("Get sum post brah.")
+ resource.headers({ "head" => "tail" })
end
it "returns the url as its identity" do
- expect(@resource.identity).to eq("http://www.trololol.net")
+ expect(resource.identity).to eq("http://www.trololol.net")
end
end
diff --git a/spec/unit/resource/ifconfig_spec.rb b/spec/unit/resource/ifconfig_spec.rb
index 699ebf1233..3221d0b864 100644
--- a/spec/unit/resource/ifconfig_spec.rb
+++ b/spec/unit/resource/ifconfig_spec.rb
@@ -55,7 +55,7 @@ describe Chef::Resource::Ifconfig do
@node.automatic_attrs[:platform_version] = version
end
- it "should use an ordinary Provider::Ifconfig as a provider for #{platform} #{version}" do
+ it "uses an ordinary Provider::Ifconfig as a provider for #{platform} #{version}" do
expect(@resource.provider_for_action(:add).class).to eq(Chef::Provider::Ifconfig)
end
end
@@ -68,7 +68,7 @@ describe Chef::Resource::Ifconfig do
@node.automatic_attrs[:platform_version] = version
end
- it "should use an Provider::Ifconfig::Redhat as a provider for #{platform} #{version}" do
+ it "uses an Provider::Ifconfig::Redhat as a provider for #{platform} #{version}" do
expect(@resource.provider_for_action(:add)).to be_a_kind_of(Chef::Provider::Ifconfig::Redhat)
end
end
@@ -81,7 +81,7 @@ describe Chef::Resource::Ifconfig do
@node.automatic_attrs[:platform_version] = version
end
- it "should use an Ifconfig::Debian as a provider for #{platform} #{version}" do
+ it "uses an Ifconfig::Debian as a provider for #{platform} #{version}" do
expect(@resource.provider_for_action(:add)).to be_a_kind_of(Chef::Provider::Ifconfig::Debian)
end
end
diff --git a/spec/unit/resource/ips_package_spec.rb b/spec/unit/resource/ips_package_spec.rb
index fd1fe2840c..9ec27e914f 100644
--- a/spec/unit/resource/ips_package_spec.rb
+++ b/spec/unit/resource/ips_package_spec.rb
@@ -17,10 +17,8 @@
#
require "spec_helper"
-require "support/shared/unit/resource/static_provider_resolution"
-
-describe Chef::Resource::IpsPackage, "initialize" do
+describe Chef::Resource::IpsPackage do
static_provider_resolution(
resource: Chef::Resource::IpsPackage,
provider: Chef::Provider::Package::Ips,
@@ -29,12 +27,28 @@ describe Chef::Resource::IpsPackage, "initialize" do
os: "solaris2"
)
- before(:each) do
- @resource = Chef::Resource::IpsPackage.new("crypto/gnupg")
+ let(:resource) { Chef::Resource::IpsPackage.new("crypto/gnupg") }
+
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
end
it "should support accept_license" do
- @resource.accept_license(true)
- expect(@resource.accept_license).to eql(true)
+ resource.accept_license(true)
+ expect(resource.accept_license).to eql(true)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
end
diff --git a/spec/unit/resource/kernel_module_spec.rb b/spec/unit/resource/kernel_module_spec.rb
new file mode 100644
index 0000000000..03cda28471
--- /dev/null
+++ b/spec/unit/resource/kernel_module_spec.rb
@@ -0,0 +1,48 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::KernelModule do
+ let(:resource) { Chef::Resource::KernelModule.new("foo") }
+
+ it "sets resource name as :kernel_module" do
+ expect(resource.resource_name).to eql(:kernel_module)
+ end
+
+ it "is not a preview resource in Chef 15" do
+ pending("Chef 15") unless Chef::VERSION.start_with?("15")
+ expect(resource.class.preview_resource).to be_falsey
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "sets the modname property as its name property" do
+ expect(resource.modname).to eql("foo")
+ end
+
+ it "supports :create and :flush actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :uninstall }.not_to raise_error
+ expect { resource.action :blacklist }.not_to raise_error
+ expect { resource.action :load }.not_to raise_error
+ expect { resource.action :unload }.not_to raise_error
+ expect { resource.action :delete }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/ksh_spec.rb b/spec/unit/resource/ksh_spec.rb
index 6c3ba291b4..30b16b8354 100644
--- a/spec/unit/resource/ksh_spec.rb
+++ b/spec/unit/resource/ksh_spec.rb
@@ -20,21 +20,26 @@ require "spec_helper"
describe Chef::Resource::Ksh do
- before(:each) do
- @resource = Chef::Resource::Ksh.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::Ksh.new("fakey_fakerton") }
+
+ it "is a subclass of Chef::Resource::Script" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Script)
+ end
+
+ it "has a resource name of :ksh" do
+ expect(resource.resource_name).to eql(:ksh)
end
- it "should create a new Chef::Resource::Ksh" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Ksh)
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
- it "should have a resource name of :ksh" do
- expect(@resource.resource_name).to eql(:ksh)
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
end
- it "should have an interpreter of ksh" do
- expect(@resource.interpreter).to eql("ksh")
+ it "has an interpreter of ksh" do
+ expect(resource.interpreter).to eql("ksh")
end
end
diff --git a/spec/unit/resource/launchd_spec.rb b/spec/unit/resource/launchd_spec.rb
index 98d21a8234..bf3fd39952 100644
--- a/spec/unit/resource/launchd_spec.rb
+++ b/spec/unit/resource/launchd_spec.rb
@@ -1,32 +1,40 @@
#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
require "spec_helper"
describe Chef::Resource::Launchd do
- @launchd = Chef::Resource::Launchd.new("io.chef.chef-client")
- let(:resource) do
- Chef::Resource::Launchd.new(
- "io.chef.chef-client",
- run_context
- ) end
+ let(:resource) { Chef::Resource::Launchd.new("fakey_fakerton" ) }
- it "should create a new Chef::Resource::Launchd" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::Launchd)
+ it "has a resource name of Launchd" do
+ expect(resource.resource_name).to eql(:launchd)
end
- it "should have a resource name of Launchd" do
- expect(resource.resource_name).to eql(:launchd)
+ it "the label property is the name_property" do
+ expect(resource.label).to eql("fakey_fakerton")
end
- it "should have a default action of create" do
+ it "sets the default action as :create" do
expect(resource.action).to eql([:create])
end
- it "should accept enable, disable, create, and delete as actions" do
- expect { resource.action :enable }.not_to raise_error
- expect { resource.action :disable }.not_to raise_error
+ it "supports :create, :create_if_missing, :delete, :disable, :enable, :restart actions" do
expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ expect { resource.action :restart }.not_to raise_error
end
end
diff --git a/spec/unit/resource/link_spec.rb b/spec/unit/resource/link_spec.rb
index adfd0020f5..05a39835d8 100644
--- a/spec/unit/resource/link_spec.rb
+++ b/spec/unit/resource/link_spec.rb
@@ -20,115 +20,105 @@
require "spec_helper"
describe Chef::Resource::Link do
+ let(:resource) { Chef::Resource::Link.new("fakey_fakerton") }
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")
end
- it "should create a new Chef::Resource::Link" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Link)
+ it "the target_file property is the name_property" do
+ expect(resource.target_file).to eql("fakey_fakerton")
end
- it "should have a name" do
- expect(@resource.name).to eql("fakey_fakerton")
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should have a default action of 'create'" do
- expect(@resource.action).to eql([:create])
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
end
- { :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)
- else
- expect { @resource.action action }.not_to raise_error
- end
- end
- end
-
- it "should use the object name as the target_file by default" do
- expect(@resource.target_file).to eql("fakey_fakerton")
+ it "uses the object name as the target_file by default" do
+ expect(resource.target_file).to eql("fakey_fakerton")
end
- it "should accept a delayed evaluator as the target path" do
- @resource.target_file Chef::DelayedEvaluator.new { "my_lazy_name" }
- expect(@resource.target_file).to eql("my_lazy_name")
+ it "accepts a delayed evaluator as the target path" do
+ resource.target_file Chef::DelayedEvaluator.new { "my_lazy_name" }
+ expect(resource.target_file).to eql("my_lazy_name")
end
- it "should accept a delayed evaluator when accessing via 'path'" do
- @resource.target_file Chef::DelayedEvaluator.new { "my_lazy_name" }
- expect(@resource.path).to eql("my_lazy_name")
+ it "accepts a delayed evaluator when accessing via 'path'" do
+ resource.target_file Chef::DelayedEvaluator.new { "my_lazy_name" }
+ expect(resource.path).to eql("my_lazy_name")
end
- it "should accept a delayed evaluator via 'to'" do
- @resource.to Chef::DelayedEvaluator.new { "my_lazy_name" }
- expect(@resource.to).to eql("my_lazy_name")
+ it "accepts a delayed evaluator via 'to'" do
+ resource.to Chef::DelayedEvaluator.new { "my_lazy_name" }
+ expect(resource.to).to eql("my_lazy_name")
end
- it "should accept a string as the link source via 'to'" do
- expect { @resource.to "/tmp" }.not_to raise_error
+ it "accepts a string as the link source via 'to'" do
+ expect { resource.to "/tmp" }.not_to raise_error
end
- it "should not accept a Hash for the link source via 'to'" do
- expect { @resource.to Hash.new }.to raise_error(ArgumentError)
+ it "does not accept a Hash for the link source via 'to'" do
+ expect { resource.to Hash.new }.to raise_error(ArgumentError)
end
- it "should allow you to set a link source via 'to'" do
- @resource.to "/tmp/foo"
- expect(@resource.to).to eql("/tmp/foo")
+ it "allows you to set a link source via 'to'" do
+ resource.to "/tmp/foo"
+ expect(resource.to).to eql("/tmp/foo")
end
- it "should allow you to specify the link type" do
- @resource.link_type "symbolic"
- expect(@resource.link_type).to eql(:symbolic)
+ it "allows you to specify the link type" do
+ resource.link_type "symbolic"
+ expect(resource.link_type).to eql(:symbolic)
end
- it "should default to a symbolic link" do
- expect(@resource.link_type).to eql(:symbolic)
+ it "defaults to a symbolic link" do
+ expect(resource.link_type).to eql(:symbolic)
end
- it "should accept a hard link_type" do
- @resource.link_type :hard
- expect(@resource.link_type).to eql(:hard)
+ it "accepts a hard link_type" do
+ resource.link_type :hard
+ expect(resource.link_type).to eql(:hard)
end
- it "should reject any other link_type but :hard and :symbolic" do
- expect { @resource.link_type "x-men" }.to raise_error(ArgumentError)
+ it "rejects any other link_type but :hard and :symbolic" do
+ expect { resource.link_type "x-men" }.to raise_error(ArgumentError)
end
- it "should accept a group name or id for group" do
- expect { @resource.group "root" }.not_to raise_error
- expect { @resource.group 123 }.not_to raise_error
- expect { @resource.group "root:goo" }.to raise_error(ArgumentError)
+ it "accepts a group name or id for group" do
+ expect { resource.group "root" }.not_to raise_error
+ expect { resource.group 123 }.not_to raise_error
+ expect { resource.group "root:goo" }.to raise_error(ArgumentError)
end
- it "should accept a user name or id for owner" do
- expect { @resource.owner "root" }.not_to raise_error
- expect { @resource.owner 123 }.not_to raise_error
- expect { @resource.owner "root:goo" }.to raise_error(ArgumentError)
+ it "accepts a user name or id for owner" do
+ expect { resource.owner "root" }.not_to raise_error
+ expect { resource.owner 123 }.not_to raise_error
+ expect { resource.owner "root:goo" }.to raise_error(ArgumentError)
end
describe "when it has to, link_type, owner, and group" do
before do
- @resource.target_file("/var/target.tar")
- @resource.to("/to/dir/file.tar")
- @resource.link_type(:symbolic)
- @resource.owner("root")
- @resource.group("0664")
+ resource.target_file("/var/target.tar")
+ resource.to("/to/dir/file.tar")
+ resource.link_type(:symbolic)
+ resource.owner("root")
+ resource.group("0664")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:to]).to eq("/to/dir/file.tar")
expect(state[:owner]).to eq("root")
expect(state[:group]).to eq("0664")
end
it "returns the target file as its identity" do
- expect(@resource.identity).to eq("/var/target.tar")
+ expect(resource.identity).to eq("/var/target.tar")
end
end
end
diff --git a/spec/unit/resource/log_spec.rb b/spec/unit/resource/log_spec.rb
index 18a1eb65bf..1e053113c6 100644
--- a/spec/unit/resource/log_spec.rb
+++ b/spec/unit/resource/log_spec.rb
@@ -21,53 +21,44 @@ 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)
- end
-
- it "should create a new Chef::Resource::Log" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Log)
- end
+ let(:log_str) { "this is my string to log" }
+ let(:resource) { Chef::Resource::Log.new(log_str) }
- it "supports the :write actions" do
- expect(@resource.allowed_actions).to include(:write)
+ it "has a name of log" do
+ expect(resource.resource_name).to eq(:log)
end
- it "should have a name of log" do
- expect(@resource.resource_name).to eq(:log)
+ it "the message property is the name_property" do
+ expect(resource.message).to eql("this is my string to log")
end
- it "should allow you to set a log string" do
- expect(@resource.name).to eq(@log_str)
+ it "sets the default action as :write" do
+ expect(resource.action).to eql([:write])
end
- it "should set the message to the first argument to new" do
- expect(@resource.message).to eq(@log_str)
+ it "supports :write action" do
+ expect { resource.action :write }.not_to raise_error
end
- it "should accept a string for the log message" do
- @resource.message "this is different"
- expect(@resource.message).to eq("this is different")
+ it "accepts a string for the log message" do
+ resource.message "this is different"
+ expect(resource.message).to eq("this is different")
end
- it "should accept a vaild level option" do
- @resource.level :debug
- @resource.level :info
- @resource.level :warn
- @resource.level :error
- @resource.level :fatal
- expect { @resource.level :unsupported }.to raise_error(ArgumentError)
+ it "accepts a vaild level option" do
+ resource.level :debug
+ resource.level :info
+ resource.level :warn
+ resource.level :error
+ resource.level :fatal
+ expect { resource.level :unsupported }.to raise_error(ArgumentError)
end
describe "when the identity is defined" do
- before do
- @resource = Chef::Resource::Log.new("ery day I'm loggin-in")
- end
+ let(:resource) { Chef::Resource::Log.new("ery day I'm loggin-in") }
it "returns the log string as its identity" do
- expect(@resource.identity).to eq("ery day I'm loggin-in")
+ expect(resource.identity).to eq("ery day I'm loggin-in")
end
end
end
diff --git a/spec/unit/resource/timestamped_deploy_spec.rb b/spec/unit/resource/macos_user_defaults_spec.rb
index 5a2dc8ae02..0ce0517bdb 100644
--- a/spec/unit/resource/timestamped_deploy_spec.rb
+++ b/spec/unit/resource/macos_user_defaults_spec.rb
@@ -1,6 +1,5 @@
#
-# Author:: Daniel DeLeo (<dan@kallistec.com>)
-# Copyright:: Copyright 2009-2016, Daniel DeLeo
+# Copyright:: Copyright 2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,15 +17,19 @@
require "spec_helper"
-describe Chef::Resource::TimestampedDeploy, "initialize" do
+describe Chef::Resource::MacosUserDefaults do
- static_provider_resolution(
- resource: Chef::Resource::TimestampedDeploy,
- provider: Chef::Provider::Deploy::Timestamped,
- name: :timestamped_deploy,
- action: :deploy,
- os: "linux",
- platform_family: "rhel"
- )
+ let(:resource) { Chef::Resource::MacosUserDefaults.new("foo") }
+ it "has a resource name of :macos_userdefaults" do
+ expect(resource.resource_name).to eql(:macos_userdefaults)
+ end
+
+ it "sets the default action as :write" do
+ expect(resource.action).to eql([:write])
+ end
+
+ it "supports :write action" do
+ expect { resource.action :write }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/macports_package_spec.rb b/spec/unit/resource/macports_package_spec.rb
index 62346def2d..dfb30d16a7 100644
--- a/spec/unit/resource/macports_package_spec.rb
+++ b/spec/unit/resource/macports_package_spec.rb
@@ -30,3 +30,22 @@ describe Chef::Resource::MacportsPackage, "initialize" do
)
end
+
+describe Chef::Resource::MacportsPackage, "defaults" do
+ let(:resource) { Chef::Resource::MacportsPackage.new("foo") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+end
diff --git a/spec/unit/resource/mdadm_spec.rb b/spec/unit/resource/mdadm_spec.rb
index f3cadbe499..d2e3c37de8 100644
--- a/spec/unit/resource/mdadm_spec.rb
+++ b/spec/unit/resource/mdadm_spec.rb
@@ -21,86 +21,83 @@ require "spec_helper"
describe Chef::Resource::Mdadm do
- before(:each) do
- @resource = Chef::Resource::Mdadm.new("fakey_fakerton")
- end
+ let(:resource) { Chef::Resource::Mdadm.new("fakey_fakerton") }
- it "should create a new Chef::Resource::Mdadm" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Mdadm)
+ it "has a resource name of :mdadm" do
+ expect(resource.resource_name).to eql(:mdadm)
end
- it "should have a resource name of :mdadm" do
- expect(@resource.resource_name).to eql(:mdadm)
+ it "the raid_device property is the name_property" do
+ expect(resource.raid_device).to eql("fakey_fakerton")
end
- it "should have a default action of create" do
- expect(@resource.action).to eql([:create])
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should accept create, assemble, stop as actions" do
- expect { @resource.action :create }.not_to raise_error
- expect { @resource.action :assemble }.not_to raise_error
- expect { @resource.action :stop }.not_to raise_error
+ it "supports :assemble, :create, :stop actions" do
+ expect { resource.action :assemble }.not_to raise_error
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :stop }.not_to raise_error
end
- it "should allow you to set the raid_device attribute" do
- @resource.raid_device "/dev/md3"
- expect(@resource.raid_device).to eql("/dev/md3")
+ it "allows you to set the raid_device attribute" do
+ resource.raid_device "/dev/md3"
+ expect(resource.raid_device).to eql("/dev/md3")
end
- it "should allow you to set the chunk attribute" do
- @resource.chunk 256
- expect(@resource.chunk).to eql(256)
+ it "allows you to set the chunk attribute" do
+ resource.chunk 256
+ expect(resource.chunk).to eql(256)
end
- it "should allow you to set the level attribute" do
- @resource.level 1
- expect(@resource.level).to eql(1)
+ it "allows you to set the level attribute" do
+ resource.level 1
+ expect(resource.level).to eql(1)
end
- it "should allow you to set the metadata attribute" do
- @resource.metadata "1.2"
- expect(@resource.metadata).to eql("1.2")
+ it "allows you to set the metadata attribute" do
+ resource.metadata "1.2"
+ expect(resource.metadata).to eql("1.2")
end
- it "should allow you to set the bitmap attribute" do
- @resource.bitmap "internal"
- expect(@resource.bitmap).to eql("internal")
+ it "allows you to set the bitmap attribute" do
+ resource.bitmap "internal"
+ expect(resource.bitmap).to eql("internal")
end
- it "should allow you to set the layout attribute" do
- @resource.layout "f2"
- expect(@resource.layout).to eql("f2")
+ it "allows you to set the layout attribute" do
+ resource.layout "f2"
+ expect(resource.layout).to eql("f2")
end
- it "should allow you to set the devices attribute" do
- @resource.devices ["/dev/sda", "/dev/sdb"]
- expect(@resource.devices).to eql(["/dev/sda", "/dev/sdb"])
+ it "allows you to set the devices attribute" do
+ resource.devices ["/dev/sda", "/dev/sdb"]
+ expect(resource.devices).to eql(["/dev/sda", "/dev/sdb"])
end
- it "should allow you to set the exists attribute" do
- @resource.exists true
- expect(@resource.exists).to eql(true)
+ it "allows you to set the exists attribute" do
+ resource.exists true
+ expect(resource.exists).to eql(true)
end
describe "when it has devices, level, and chunk" do
before do
- @resource.raid_device("raider")
- @resource.devices(%w{device1 device2})
- @resource.level(1)
- @resource.chunk(42)
+ resource.raid_device("raider")
+ resource.devices(%w{device1 device2})
+ resource.level(1)
+ resource.chunk(42)
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:devices]).to eql(%w{device1 device2})
expect(state[:level]).to eq(1)
expect(state[:chunk]).to eq(42)
end
it "returns the raid device as its identity" do
- expect(@resource.identity).to eq("raider")
+ expect(resource.identity).to eq("raider")
end
end
diff --git a/spec/unit/resource/mount_spec.rb b/spec/unit/resource/mount_spec.rb
index 466b6ac8c0..ec6fb1232a 100644
--- a/spec/unit/resource/mount_spec.rb
+++ b/spec/unit/resource/mount_spec.rb
@@ -20,196 +20,159 @@
require "spec_helper"
describe Chef::Resource::Mount do
- before(:each) do
- @resource = Chef::Resource::Mount.new("filesystem")
- end
+ let(:resource) { Chef::Resource::Mount.new("fakey_fakerton") }
- it "should create a new Chef::Resource::Mount" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Mount)
+ it "the mount_point property is the name_property" do
+ expect(resource.mount_point).to eql("fakey_fakerton")
end
- it "should have a name" do
- expect(@resource.name).to eql("filesystem")
+ it "sets the default action as :mount" do
+ expect(resource.action).to eql([:mount])
end
- it "should set mount_point to the name" do
- expect(@resource.mount_point).to eql("filesystem")
+ it "supports :disable, :enable, :mount, :remount, :umount, :unmount actions" do
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ expect { resource.action :mount }.not_to raise_error
+ expect { resource.action :remount }.not_to raise_error
+ expect { resource.action :umount }.not_to raise_error
+ expect { resource.action :unmount }.not_to raise_error
end
- it "should have a default action of mount" do
- expect(@resource.action).to eql([:mount])
+ it "allows you to set the device property" do
+ resource.device "/dev/sdb3"
+ expect(resource.device).to eql("/dev/sdb3")
end
- it "should accept mount, umount, unmount and remount as actions" do
- expect { @resource.action :mount }.not_to raise_error
- expect { @resource.action :umount }.not_to raise_error
- expect { @resource.action :unmount }.not_to raise_error
- expect { @resource.action :remount }.not_to raise_error
- expect { @resource.action :brooklyn }.to raise_error(ArgumentError)
+ it "allows you to set mount_point property" do
+ resource.mount_point "U:"
+ expect(resource.mount_point).to eql("U:")
end
- it "should allow you to set the device attribute" do
- @resource.device "/dev/sdb3"
- expect(@resource.device).to eql("/dev/sdb3")
+ it "raises error when mount_point property is not set" do
+ resource.mount_point nil
+ expect { resource.mounted("poop") }.to raise_error(ArgumentError)
end
- it "should set fsck_device to '-' by default" do
- expect(@resource.fsck_device).to eql("-")
+ it "sets fsck_device to '-' by default" do
+ expect(resource.fsck_device).to eql("-")
end
- it "should allow you to set the fsck_device attribute" do
- @resource.fsck_device "/dev/rdsk/sdb3"
- expect(@resource.fsck_device).to eql("/dev/rdsk/sdb3")
+ it "allows you to set the fsck_device property" do
+ resource.fsck_device "/dev/rdsk/sdb3"
+ expect(resource.fsck_device).to eql("/dev/rdsk/sdb3")
end
- it "should allow you to set the fstype attribute" do
- @resource.fstype "nfs"
- expect(@resource.fstype).to eql("nfs")
+ it "allows you to set the fstype property" do
+ resource.fstype "nfs"
+ expect(resource.fstype).to eql("nfs")
end
- it "should allow you to set the dump attribute" do
- @resource.dump 1
- expect(@resource.dump).to eql(1)
+ it "sets fstype to 'auto' by default" do
+ expect(resource.fstype).to eql("auto")
end
- it "should allow you to set the pass attribute" do
- @resource.pass 1
- expect(@resource.pass).to eql(1)
+ it "allows you to set the dump property" do
+ resource.dump 1
+ expect(resource.dump).to eql(1)
end
- it "should set the options attribute to defaults" do
- expect(@resource.options).to eql(["defaults"])
+ it "allows you to set the pass property" do
+ resource.pass 1
+ expect(resource.pass).to eql(1)
end
- it "should allow options to be sent as a string, and convert to array" do
- @resource.options "rw,noexec"
- expect(@resource.options).to be_a_kind_of(Array)
+ it "sets the options property to defaults" do
+ expect(resource.options).to eql(["defaults"])
end
- it "should allow options attribute as an array" do
- @resource.options %w{ro nosuid}
- expect(@resource.options).to be_a_kind_of(Array)
+ it "allows options to be sent as a string, and convert to array" do
+ resource.options "rw,noexec"
+ expect(resource.options).to be_a_kind_of(Array)
end
- it "should allow options to be sent as a delayed evaluator" do
- @resource.options Chef::DelayedEvaluator.new { %w{rw noexec} }
- expect(@resource.options).to eql(%w{rw noexec})
+ it "allows options property as an array" do
+ resource.options %w{ro nosuid}
+ expect(resource.options).to be_a_kind_of(Array)
end
- it "should allow options to be sent as a delayed evaluator, and convert to array" do
- @resource.options Chef::DelayedEvaluator.new { "rw,noexec" }
- expect(@resource.options).to be_a_kind_of(Array)
- expect(@resource.options).to eql(%w{rw noexec})
+ it "allows options to be sent as a delayed evaluator" do
+ resource.options Chef::DelayedEvaluator.new { %w{rw noexec} }
+ expect(resource.options).to eql(%w{rw noexec})
end
- it "should accept true for mounted" do
- @resource.mounted(true)
- expect(@resource.mounted).to eql(true)
+ it "allows options to be sent as a delayed evaluator, and convert to array" do
+ resource.options Chef::DelayedEvaluator.new { "rw,noexec" }
+ expect(resource.options).to be_a_kind_of(Array)
+ expect(resource.options).to eql(%w{rw noexec})
end
- it "should accept false for mounted" do
- @resource.mounted(false)
- expect(@resource.mounted).to eql(false)
+ it "accepts true for mounted" do
+ resource.mounted(true)
+ expect(resource.mounted).to eql(true)
end
- it "should set mounted to false by default" do
- expect(@resource.mounted).to eql(false)
+ it "accepts false for mounted" do
+ resource.mounted(false)
+ expect(resource.mounted).to eql(false)
end
- it "should not accept a string for mounted" do
- expect { @resource.mounted("poop") }.to raise_error(ArgumentError)
+ it "sets mounted to false by default" do
+ expect(resource.mounted).to eql(false)
end
- it "should accept true for enabled" do
- @resource.enabled(true)
- expect(@resource.enabled).to eql(true)
+ it "does not accept a string for mounted" do
+ expect { resource.mounted("poop") }.to raise_error(ArgumentError)
end
- it "should accept false for enabled" do
- @resource.enabled(false)
- expect(@resource.enabled).to eql(false)
+ it "accepts true for enabled" do
+ resource.enabled(true)
+ expect(resource.enabled).to eql(true)
end
- it "should set enabled to false by default" do
- expect(@resource.enabled).to eql(false)
+ it "accepts false for enabled" do
+ resource.enabled(false)
+ expect(resource.enabled).to eql(false)
end
- it "should not accept a string for enabled" do
- expect { @resource.enabled("poop") }.to raise_error(ArgumentError)
+ it "sets enabled to false by default" do
+ expect(resource.enabled).to eql(false)
end
- it "should default all feature support to false" do
- support_hash = { :remount => false }
- expect(@resource.supports).to eq(support_hash)
+ it "does not accept a string for enabled" do
+ expect { resource.enabled("poop") }.to raise_error(ArgumentError)
end
- it "should allow you to set feature support as an array" do
- support_array = [ :remount ]
- support_hash = { :remount => true }
- @resource.supports(support_array)
- expect(@resource.supports).to eq(support_hash)
+ it "defaults all feature support to false" do
+ support_hash = { remount: false }
+ expect(resource.supports).to eq(support_hash)
end
- it "should allow you to set feature support as a hash" do
- support_hash = { :remount => true }
- @resource.supports(support_hash)
- expect(@resource.supports).to eq(support_hash)
+ it "allows you to set feature support as an array" do
+ support_array = [ :remount ]
+ support_hash = { remount: true }
+ resource.supports(support_array)
+ expect(resource.supports).to eq(support_hash)
end
- it "should allow you to set username" do
- @resource.username("Administrator")
- expect(@resource.username).to eq("Administrator")
+ it "allows you to set feature support as a hash" do
+ support_hash = { remount: true }
+ resource.supports(support_hash)
+ expect(resource.supports).to eq(support_hash)
end
- it "should allow you to set password" do
- @resource.password("Jetstream123!")
- expect(@resource.password).to eq("Jetstream123!")
+ it "allows you to set username" do
+ resource.username("Administrator")
+ expect(resource.username).to eq("Administrator")
end
- it "should allow you to set domain" do
- @resource.domain("TEST_DOMAIN")
- expect(@resource.domain).to eq("TEST_DOMAIN")
+ it "allows you to set password" do
+ resource.password("Jetstream123!")
+ expect(resource.password).to eq("Jetstream123!")
end
- describe "when it has mount point, device type, and fstype" do
- before do
- @resource.device("charmander")
- @resource.mount_point("123.456")
- @resource.device_type(:device)
- @resource.fstype("ranked")
- end
-
- it "describes its state" do
- state = @resource.state_for_resource_reporter
- expect(state[:mount_point]).to eq("123.456")
- expect(state[:device_type]).to eql(:device)
- expect(state[:fstype]).to eq("ranked")
- end
-
- it "returns the device as its identity" do
- expect(@resource.identity).to eq("charmander")
- end
- end
-
- describe "when it has username, password and domain" do
- before do
- @resource.mount_point("T:")
- @resource.device("charmander")
- @resource.username("Administrator")
- @resource.password("Jetstream123!")
- @resource.domain("TEST_DOMAIN")
- end
-
- it "describes its state" do
- state = @resource.state_for_resource_reporter
- expect(state[:mount_point]).to eq("T:")
- expect(state[:username]).to eq("Administrator")
- expect(state[:password]).to eq("Jetstream123!")
- expect(state[:domain]).to eq("TEST_DOMAIN")
- expect(state[:device_type]).to eql(:device)
- expect(state[:fstype]).to eq("auto")
- end
-
+ it "allows you to set domain" do
+ resource.domain("TEST_DOMAIN")
+ expect(resource.domain).to eq("TEST_DOMAIN")
end
end
diff --git a/spec/unit/resource/msu_package_spec.rb b/spec/unit/resource/msu_package_spec.rb
index 349a382b31..843c2ca49d 100644
--- a/spec/unit/resource/msu_package_spec.rb
+++ b/spec/unit/resource/msu_package_spec.rb
@@ -21,29 +21,43 @@ require "spec_helper"
describe Chef::Resource::MsuPackage do
let(:resource) { Chef::Resource::MsuPackage.new("test_pkg") }
- it "creates a new Chef::Resource::MsuPackage" do
- expect(resource).to be_a_kind_of(Chef::Resource)
+ it "is a subclass of Chef::Resource::Package" do
expect(resource).to be_a_kind_of(Chef::Resource::Package)
- expect(resource).to be_a_instance_of(Chef::Resource::MsuPackage)
end
it "sets resource name as :msu_package" do
expect(resource.resource_name).to eql(:msu_package)
end
- it "sets the source as it's name" do
- expect(resource.source).to eql("test_pkg")
- end
-
it "sets the default action as :install" do
- expect(resource.action).to eql(:install)
+ expect(resource.action).to eql([:install])
end
- it "raises error if invalid action is given" do
- expect { resource.action "abc" }.to raise_error(Chef::Exceptions::ValidationFailed)
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
- it "coerce its name to a package_name" do
+ it "coerces name property to package_name property" do
expect(resource.package_name).to eql("test_pkg")
end
+
+ it "coerces name property to a source property if source not provided" do
+ expect(resource.source).to end_with("test_pkg")
+ end
+
+ it "coerces name property to a source property if source not provided and package_name is" do
+ resource.package_name("package.msu")
+ expect(resource.source).to end_with("package.msu")
+ end
+
+ it "coerces source property if it does not looks like a path" do
+ resource.source("package.msu")
+ expect(resource.source).not_to eq("package.msu")
+ end
end
diff --git a/spec/unit/resource/ohai_hint_spec.rb b/spec/unit/resource/ohai_hint_spec.rb
new file mode 100644
index 0000000000..87cfe5e721
--- /dev/null
+++ b/spec/unit/resource/ohai_hint_spec.rb
@@ -0,0 +1,44 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::OhaiHint do
+
+ let(:resource) { Chef::Resource::OhaiHint.new("fakey_fakerton") }
+
+ it "has a resource name of :ohai_hint" do
+ expect(resource.resource_name).to eql(:ohai_hint)
+ end
+
+ it "the hint_name property is the name_property" do
+ expect(resource.hint_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ end
+
+ it "runs at compile_time by default" do
+ expect(resource.compile_time).to eql(true)
+ end
+end
diff --git a/spec/unit/resource/ohai_spec.rb b/spec/unit/resource/ohai_spec.rb
index 574c09eeba..a18929da15 100644
--- a/spec/unit/resource/ohai_spec.rb
+++ b/spec/unit/resource/ohai_spec.rb
@@ -20,41 +20,42 @@ require "spec_helper"
describe Chef::Resource::Ohai do
- before(:each) do
- @resource = Chef::Resource::Ohai.new("ohai_reload")
+ let(:resource) { Chef::Resource::Ohai.new("fakey_fakerton") }
+
+ it "has a resource name of :ohai" do
+ expect(resource.resource_name).to eql(:ohai)
end
- it "should create a new Chef::Resource::Ohai" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Ohai)
+ it "the ohai_name property is the name_property" do
+ expect(resource.ohai_name).to eql("fakey_fakerton")
end
- it "should have a resource name of :ohai" do
- expect(@resource.resource_name).to eql(:ohai)
+ it "sets the default action as :reload" do
+ expect(resource.action).to eql([:reload])
end
- it "should have a default action of reload" do
- expect(@resource.action).to eql([:reload])
+ it "supports :reload action" do
+ expect { resource.action :reload }.not_to raise_error
end
- it "should allow you to set the plugin attribute" do
- @resource.plugin "passwd"
- expect(@resource.plugin).to eql("passwd")
+ it "allows you to set the plugin property" do
+ resource.plugin "passwd"
+ expect(resource.plugin).to eql("passwd")
end
describe "when it has a plugin value" do
before do
- @resource.name("test")
- @resource.plugin("passwd")
+ resource.name("test")
+ resource.plugin("passwd")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:plugin]).to eq("passwd")
end
it "returns the name as its identity" do
- expect(@resource.identity).to eq("test")
+ expect(resource.identity).to eq("test")
end
end
diff --git a/spec/unit/resource/openbsd_package_spec.rb b/spec/unit/resource/openbsd_package_spec.rb
index 9bdc823576..935cc11b40 100644
--- a/spec/unit/resource/openbsd_package_spec.rb
+++ b/spec/unit/resource/openbsd_package_spec.rb
@@ -20,28 +20,38 @@
#
require "spec_helper"
-require "ostruct"
describe Chef::Resource::OpenbsdPackage do
-
- before(:each) do
- @node = Chef::Node.new
- @events = Chef::EventDispatch::Dispatcher.new
- @run_context = Chef::RunContext.new(@node, {}, @events)
- @resource = Chef::Resource::OpenbsdPackage.new("foo", @run_context)
- end
+ let(:node) { Chef::Node.new }
+ let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:run_context) { Chef::RunContext.new(node, {}, events) }
+ let(:resource) { Chef::Resource::OpenbsdPackage.new("foo", run_context) }
describe "Initialization" do
- it "should return a Chef::Resource::OpenbsdPackage" do
- expect(@resource).to be_a_kind_of(Chef::Resource::OpenbsdPackage)
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
+ end
+
+ it "sets the resource_name to :openbsd_package" do
+ expect(resource.resource_name).to eql(:openbsd_package)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should set the resource_name to :openbsd_package" do
- expect(@resource.resource_name).to eql(:openbsd_package)
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
- it "should not set the provider" do
- expect(@resource.provider).to be_nil
+ it "does not set the provider" do
+ expect(resource.provider).to be_nil
end
end
diff --git a/spec/unit/resource/openssl_dhparam.rb b/spec/unit/resource/openssl_dhparam.rb
new file mode 100644
index 0000000000..10c5399c33
--- /dev/null
+++ b/spec/unit/resource/openssl_dhparam.rb
@@ -0,0 +1,56 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::OpensslDhparam do
+
+ let(:resource) { Chef::Resource::OpensslDhparam.new("fakey_fakerton") }
+
+ it "has a resource name of :openssl_dhparam" do
+ expect(resource.resource_name).to eql(:openssl_dhparam)
+ end
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create action" do
+ expect { resource.action :create }.not_to raise_error
+ end
+
+ it "has a default mode of '0640'" do
+ expect(resource.mode).to eql("0640")
+ end
+
+ it "has a default generator of 2" do
+ expect(resource.generator).to eql(2)
+ end
+
+ it "has a default key_length of 2048" do
+ expect(resource.key_length).to eql(2048)
+ end
+
+ it "only accepts valid key length" do
+ expect { resource.key_length 1234 }.to raise_error(ArgumentError)
+ end
+
+end
diff --git a/spec/unit/resource/openssl_rsa_private_key_spec.rb b/spec/unit/resource/openssl_rsa_private_key_spec.rb
new file mode 100644
index 0000000000..ceccfbcb25
--- /dev/null
+++ b/spec/unit/resource/openssl_rsa_private_key_spec.rb
@@ -0,0 +1,64 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::OpensslRsaPrivateKey do
+
+ let(:resource) { Chef::Resource::OpensslRsaPrivateKey.new("fakey_fakerton") }
+
+ it "has a resource name of :openssl_rsa_private_key" do
+ expect(resource.resource_name).to eql(:openssl_rsa_private_key)
+ end
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create action" do
+ expect { resource.action :create }.not_to raise_error
+ end
+
+ it "has a default mode of '0600'" do
+ expect(resource.mode).to eql("0600")
+ end
+
+ it "has a default key_cipher of 'des3'" do
+ expect(resource.key_cipher).to eql("des3")
+ end
+
+ it "only accepts valid key_cipher values" do
+ expect { resource.key_cipher "fako" }.to raise_error(ArgumentError)
+ end
+
+ it "has a default key_length of 2048" do
+ expect(resource.key_length).to eql(2048)
+ end
+
+ it "only accepts valid key length" do
+ expect { resource.key_length 1234 }.to raise_error(ArgumentError)
+ end
+
+ it "has a default force value of of false" do
+ expect(resource.force).to eql(false)
+ end
+
+end
diff --git a/spec/unit/resource/openssl_rsa_public_key_spec.rb b/spec/unit/resource/openssl_rsa_public_key_spec.rb
new file mode 100644
index 0000000000..5c63ce5df2
--- /dev/null
+++ b/spec/unit/resource/openssl_rsa_public_key_spec.rb
@@ -0,0 +1,43 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::OpensslRsaPublicKey do
+
+ let(:resource) { Chef::Resource::OpensslRsaPublicKey.new("key") }
+
+ it "has a resource name of :openssl_rsa_public_key" do
+ expect(resource.resource_name).to eql(:openssl_rsa_public_key)
+ end
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("key")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create action" do
+ expect { resource.action :create }.not_to raise_error
+ end
+
+ it "has a default mode of '0640'" do
+ expect(resource.mode).to eql("0640")
+ end
+end
diff --git a/spec/unit/resource/osx_profile_spec.rb b/spec/unit/resource/osx_profile_spec.rb
index 513e570e7c..3a0b144183 100644
--- a/spec/unit/resource/osx_profile_spec.rb
+++ b/spec/unit/resource/osx_profile_spec.rb
@@ -21,40 +21,38 @@ require "spec_helper"
describe Chef::Resource::OsxProfile do
let(:resource) do
Chef::Resource::OsxProfile.new(
- "Test Profile Resource",
- run_context)
+ "fakey_fakerton")
end
- it "should create a new Chef::Resource::OsxProfile" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::OsxProfile)
+ it "has a resource name of profile" do
+ expect(resource.resource_name).to eql(:osx_profile)
end
- it "should have a resource name of profile" do
- expect(resource.resource_name).to eql(:osx_profile)
+ it "the profile_name property is the name_property" do
+ expect(resource.profile_name).to eql("fakey_fakerton")
end
- it "should have a default action of install" do
+ it "sets the default action as :install" do
expect(resource.action).to eql([:install])
end
- it "should accept install and remove as actions" do
+ it "supports :install, :remove actions" do
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
+ it "allows you to set the profile attribute" do
resource.profile "com.testprofile.screensaver"
expect(resource.profile).to eql("com.testprofile.screensaver")
end
- it "should allow you to set the profile attribute to a string" do
+ it "allows you to set the profile attribute to a string" do
resource.profile "com.testprofile.screensaver"
expect(resource.profile).to be_a(String)
expect(resource.profile).to eql("com.testprofile.screensaver")
end
- it "should allow you to set the profile attribute to a hash" do
+ it "allows you to set the profile attribute to a hash" do
test_profile = { "profile" => false }
resource.profile test_profile
expect(resource.profile).to be_a(Hash)
diff --git a/spec/unit/resource/package_spec.rb b/spec/unit/resource/package_spec.rb
index 84f92f26b5..b0e1304775 100644
--- a/spec/unit/resource/package_spec.rb
+++ b/spec/unit/resource/package_spec.rb
@@ -20,84 +20,89 @@
require "spec_helper"
describe Chef::Resource::Package do
+ let(:resource) { Chef::Resource::Package.new("emacs") }
- before(:each) do
- @resource = Chef::Resource::Package.new("emacs")
+ it "sets the package_name to the first argument to new" do
+ expect(resource.package_name).to eql("emacs")
end
- it "should create a new Chef::Resource::Package" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Package)
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should set the package_name to the first argument to new" do
- expect(@resource.package_name).to eql("emacs")
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
- it "should accept a string for the package name" do
- @resource.package_name "something"
- expect(@resource.package_name).to eql("something")
+ it "accepts a string for the package name" do
+ resource.package_name "something"
+ expect(resource.package_name).to eql("something")
end
- it "should accept a string for the version" do
- @resource.version "something"
- expect(@resource.version).to eql("something")
+ it "accepts a string for the version" do
+ resource.version "something"
+ expect(resource.version).to eql("something")
end
- it "should accept a string for the response file" do
- @resource.response_file "something"
- expect(@resource.response_file).to eql("something")
+ it "accepts a string for the response file" do
+ resource.response_file "something"
+ expect(resource.response_file).to eql("something")
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 })
+ it "accepts a hash for response file template variables" do
+ 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
- @resource.source "something"
- expect(@resource.source).to eql("something")
+ it "accepts a string for the source" do
+ resource.source "something"
+ expect(resource.source).to eql("something")
end
- it "should accept a string for the options" do
- @resource.options "something"
- expect(@resource.options).to eql(["something"])
+ it "accepts a string for the options" do
+ resource.options "something"
+ expect(resource.options).to eql(["something"])
end
- it "should split options" do
- @resource.options "-a -b 'arg with spaces' -b \"and quotes\""
- expect(@resource.options).to eql(["-a", "-b", "arg with spaces", "-b", "and quotes"])
+ it "splits options" do
+ resource.options "-a -b 'arg with spaces' -b \"and quotes\""
+ expect(resource.options).to eql(["-a", "-b", "arg with spaces", "-b", "and quotes"])
end
describe "when it has a package_name and version" do
before do
- @resource.package_name("tomcat")
- @resource.version("10.9.8")
- @resource.options("-al")
+ resource.package_name("tomcat")
+ resource.version("10.9.8")
+ resource.options("-al")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:version]).to eq("10.9.8")
expect(state[:options]).to eq(["-al"])
end
it "returns the file path as its identity" do
- expect(@resource.identity).to eq("tomcat")
+ expect(resource.identity).to eq("tomcat")
end
it "takes options as an array" do
- @resource.options [ "-a", "-l" ]
- expect(@resource.options).to eq(["-a", "-l" ])
+ resource.options [ "-a", "-l" ]
+ expect(resource.options).to eq(["-a", "-l" ])
end
end
# String, Integer
[ "600", 600 ].each do |val|
it "supports setting a timeout as a #{val.class}" do
- @resource.timeout(val)
- expect(@resource.timeout).to eql(val)
+ resource.timeout(val)
+ 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 b9d2ea21f6..ecc224508f 100644
--- a/spec/unit/resource/pacman_package_spec.rb
+++ b/spec/unit/resource/pacman_package_spec.rb
@@ -1,6 +1,7 @@
#
# Author:: Jan Zimmek (<jan.zimmek@web.de>)
# Copyright:: Copyright 2010-2016, Jan Zimmek
+# Copyright:: 2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,10 +18,8 @@
#
require "spec_helper"
-require "support/shared/unit/resource/static_provider_resolution"
-
-describe Chef::Resource::PacmanPackage, "initialize" do
+describe Chef::Resource::PacmanPackage do
static_provider_resolution(
resource: Chef::Resource::PacmanPackage,
provider: Chef::Provider::Package::Pacman,
@@ -29,4 +28,19 @@ describe Chef::Resource::PacmanPackage, "initialize" do
os: "linux"
)
+ let(:resource) { Chef::Resource::PacmanPackage.new("fakey_fakerton") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/paludis_package_spec.rb b/spec/unit/resource/paludis_package_spec.rb
new file mode 100644
index 0000000000..2ee3039b13
--- /dev/null
+++ b/spec/unit/resource/paludis_package_spec.rb
@@ -0,0 +1,36 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::PaludisPackage do
+ let(:resource) { Chef::Resource::PaludisPackage.new("fakey_fakerton") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/perl_spec.rb b/spec/unit/resource/perl_spec.rb
index 417d74a8c2..ccc99d7b73 100644
--- a/spec/unit/resource/perl_spec.rb
+++ b/spec/unit/resource/perl_spec.rb
@@ -20,21 +20,25 @@ require "spec_helper"
describe Chef::Resource::Perl do
- before(:each) do
- @resource = Chef::Resource::Perl.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::Perl.new("fakey_fakerton") }
+
+ it "is a subclass of Chef::Resource::Script" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Script)
end
- it "should create a new Chef::Resource::Perl" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Perl)
+ it "has a resource name of :perl" do
+ expect(resource.resource_name).to eql(:perl)
end
- it "should have a resource name of :perl" do
- expect(@resource.resource_name).to eql(:perl)
+ it "has an interpreter of perl" do
+ expect(resource.interpreter).to eql("perl")
end
- it "should have an interpreter of perl" do
- expect(@resource.interpreter).to eql("perl")
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/portage_package_spec.rb b/spec/unit/resource/portage_package_spec.rb
index d2336744bf..7030a11d87 100644
--- a/spec/unit/resource/portage_package_spec.rb
+++ b/spec/unit/resource/portage_package_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Adam Jacob (<adam@chef.io>)
-# Copyright:: Copyright 2008-2016, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,23 +16,31 @@
# limitations under the License.
#
-require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
+require "spec_helper"
describe Chef::Resource::PortagePackage, "initialize" do
- before(:each) do
- @resource = Chef::Resource::PortagePackage.new("foo")
+ let(:resource) { Chef::Resource::PortagePackage.new("foo") }
+
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
end
- it "should return a Chef::Resource::PortagePackage" do
- expect(@resource).to be_a_kind_of(Chef::Resource::PortagePackage)
+ it "sets the resource_name to :portage_package" do
+ expect(resource.resource_name).to eql(:portage_package)
end
- it "should set the resource_name to :portage_package" do
- expect(@resource.resource_name).to eql(:portage_package)
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should set the provider to Chef::Provider::Package::Portage" do
- expect(@resource.provider).to eql(Chef::Provider::Package::Portage)
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
end
diff --git a/spec/unit/resource/powershell_package_source_spec.rb b/spec/unit/resource/powershell_package_source_spec.rb
new file mode 100644
index 0000000000..4033f4515f
--- /dev/null
+++ b/spec/unit/resource/powershell_package_source_spec.rb
@@ -0,0 +1,219 @@
+# Author:: Tor Magnus Rakvåg (tm@intility.no)
+# Copyright:: 2018, Intility AS
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::PowershellPackageSource do
+ let(:resource) { Chef::Resource::PowershellPackageSource.new("MyGallery") }
+ let(:provider) { resource.provider_for_action(:enable) }
+
+ it "has a resource name of :powershell_package_source" do
+ expect(resource.resource_name).to eql(:powershell_package_source)
+ end
+
+ it "the name_property is 'name'" do
+ expect(resource.source_name).to eql("MyGallery")
+ end
+
+ it "the default action is :register" do
+ expect(resource.action).to eql([:register])
+ end
+
+ it "supports :register and :unregister actions" do
+ expect { resource.action :register }.not_to raise_error
+ expect { resource.action :unregister }.not_to raise_error
+ end
+
+ it "the url property accepts strings" do
+ resource.url("https://mygallery.company.co/api/v2/")
+ expect(resource.url).to eql("https://mygallery.company.co/api/v2/")
+ end
+
+ it "the trusted property accepts true and false" do
+ resource.trusted(false)
+ expect(resource.trusted).to eql(false)
+ resource.trusted(true)
+ expect(resource.trusted).to eql(true)
+ end
+
+ it "trusted defaults to false" do
+ expect(resource.trusted).to eql(false)
+ end
+
+ it "provider_name accepts 'Programs', 'msi', 'NuGet', 'msu', 'PowerShellGet', 'psl', 'chocolatey'" do
+ expect { resource.provider_name("Programs") }.not_to raise_error
+ expect { resource.provider_name("msi") }.not_to raise_error
+ expect { resource.provider_name("NuGet") }.not_to raise_error
+ expect { resource.provider_name("msu") }.not_to raise_error
+ expect { resource.provider_name("PowerShellGet") }.not_to raise_error
+ expect { resource.provider_name("psl") }.not_to raise_error
+ expect { resource.provider_name("chocolatey") }.not_to raise_error
+ end
+
+ it "the publish_location property accepts strings" do
+ resource.publish_location("https://mygallery.company.co/api/v2/package")
+ expect(resource.publish_location).to eql("https://mygallery.company.co/api/v2/package")
+ end
+
+ it "the script_source_location property accepts strings" do
+ resource.publish_location("https://mygallery.company.co/api/v2/scripts")
+ expect(resource.publish_location).to eql("https://mygallery.company.co/api/v2/scripts")
+ end
+
+ it "the script_publish_location property accepts strings" do
+ resource.publish_location("https://mygallery.company.co/api/v2/scripts")
+ expect(resource.publish_location).to eql("https://mygallery.company.co/api/v2/scripts")
+ end
+
+ describe "#build_ps_repository_command" do
+ before do
+ resource.source_name("MyGallery")
+ resource.url("https://mygallery.company.co/api/v2/")
+ end
+
+ context "#register" do
+ it "builds a minimal command" do
+ expect(provider.build_ps_repository_command("Register", resource)).to eql("Register-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted'")
+ end
+
+ it "builds a command with trusted set to true" do
+ resource.trusted(true)
+ expect(provider.build_ps_repository_command("Register", resource)).to eql("Register-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Trusted'")
+ end
+
+ it "builds a command with a publish location" do
+ resource.publish_location("https://mygallery.company.co/api/v2/package")
+ expect(provider.build_ps_repository_command("Register", resource)).to eql("Register-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -PublishLocation 'https://mygallery.company.co/api/v2/package'")
+ end
+
+ it "builds a command with a script source location" do
+ resource.script_source_location("https://mygallery.company.co/api/v2/scripts")
+ expect(provider.build_ps_repository_command("Register", resource)).to eql("Register-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -ScriptSourceLocation 'https://mygallery.company.co/api/v2/scripts'")
+ end
+
+ it "builds a command with a script publish location" do
+ resource.script_publish_location("https://mygallery.company.co/api/v2/scripts/package")
+ expect(provider.build_ps_repository_command("Register", resource)).to eql("Register-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -ScriptPublishLocation 'https://mygallery.company.co/api/v2/scripts/package'")
+ end
+ end
+
+ context "#set" do
+ it "builds a minimal command" do
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted'")
+ end
+
+ it "builds a command to change the url" do
+ resource.url("https://othergallery.company.co/api/v2/")
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://othergallery.company.co/api/v2/' -InstallationPolicy 'Untrusted'")
+ end
+
+ it "builds a command with trusted set to true" do
+ resource.trusted(true)
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Trusted'")
+ end
+
+ it "builds a command with a publish location" do
+ resource.publish_location("https://mygallery.company.co/api/v2/package")
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -PublishLocation 'https://mygallery.company.co/api/v2/package'")
+ end
+
+ it "builds a command with a script source location" do
+ resource.script_source_location("https://mygallery.company.co/api/v2/scripts")
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -ScriptSourceLocation 'https://mygallery.company.co/api/v2/scripts'")
+ end
+
+ it "builds a command with a script publish location" do
+ resource.script_publish_location("https://mygallery.company.co/api/v2/scripts/package")
+ expect(provider.build_ps_repository_command("Set", resource)).to eql("Set-PSRepository -Name 'MyGallery' -SourceLocation 'https://mygallery.company.co/api/v2/' -InstallationPolicy 'Untrusted' -ScriptPublishLocation 'https://mygallery.company.co/api/v2/scripts/package'")
+ end
+ end
+ end
+
+ describe "#build_package_source_command" do
+ before do
+ resource.source_name("NuGet")
+ resource.url("http://nuget.org/api/v2/")
+ end
+
+ context "#register" do
+ it "builds a minimal command" do
+ expect(provider.build_package_source_command("Register", resource)).to eql("Register-PackageSource -Name 'NuGet' -Location 'http://nuget.org/api/v2/' -Trusted:$false -ProviderName 'NuGet'")
+ end
+
+ it "builds a command with trusted set to true" do
+ resource.trusted(true)
+ expect(provider.build_package_source_command("Register", resource)).to eql("Register-PackageSource -Name 'NuGet' -Location 'http://nuget.org/api/v2/' -Trusted:$true -ProviderName 'NuGet'")
+ end
+
+ it "builds a command with a different provider" do
+ resource.source_name("choco")
+ resource.url("https://chocolatey.org/api/v2/")
+ resource.provider_name("chocolatey")
+ expect(provider.build_package_source_command("Register", resource)).to eql("Register-PackageSource -Name 'choco' -Location 'https://chocolatey.org/api/v2/' -Trusted:$false -ProviderName 'chocolatey'")
+ end
+ end
+
+ context "#set" do
+ it "builds a minimal command" do
+ expect(provider.build_package_source_command("Set", resource)).to eql("Set-PackageSource -Name 'NuGet' -Location 'http://nuget.org/api/v2/' -Trusted:$false -ProviderName 'NuGet'")
+ end
+
+ it "builds a command to change the url" do
+ resource.url("https://nuget.company.co/api/v2/")
+ expect(provider.build_package_source_command("Set", resource)).to eql("Set-PackageSource -Name 'NuGet' -Location 'https://nuget.company.co/api/v2/' -Trusted:$false -ProviderName 'NuGet'")
+ end
+
+ it "builds a command with trusted set to true" do
+ resource.trusted(true)
+ expect(provider.build_package_source_command("Set", resource)).to eql("Set-PackageSource -Name 'NuGet' -Location 'http://nuget.org/api/v2/' -Trusted:$true -ProviderName 'NuGet'")
+ end
+
+ it "builds a command with a different provider" do
+ resource.source_name("choco")
+ resource.url("https://chocolatey.org/api/v2/")
+ resource.provider_name("chocolatey")
+ expect(provider.build_package_source_command("Set", resource)).to eql("Set-PackageSource -Name 'choco' -Location 'https://chocolatey.org/api/v2/' -Trusted:$false -ProviderName 'chocolatey'")
+ end
+ end
+ end
+
+ describe "#psrepository_cmdlet_appropriate?" do
+ it "returns true if the provider_name is 'PowerShellGet'" do
+ resource.provider_name("PowerShellGet")
+ expect(provider.psrepository_cmdlet_appropriate?).to eql(true)
+ end
+
+ it "returns false if the provider_name is something else" do
+ resource.provider_name("NuGet")
+ expect(provider.psrepository_cmdlet_appropriate?).to eql(false)
+ end
+ end
+
+ describe "#package_source_exists?" do
+ it "returns true if it exists" do
+ allow(provider).to receive(:powershell_out!).with("(Get-PackageSource -Name 'MyGallery').Name").and_return(double("powershell_out!", stdout: "MyGallery\r\n"))
+ resource.source_name("MyGallery")
+ expect(provider.package_source_exists?).to eql(true)
+ end
+
+ it "returns false if it doesn't exist" do
+ allow(provider).to receive(:powershell_out!).with("(Get-PackageSource -Name 'MyGallery').Name").and_return(double("powershell_out!", stdout: ""))
+ resource.source_name("MyGallery")
+ expect(provider.package_source_exists?).to eql(false)
+ end
+ end
+end
diff --git a/spec/unit/resource/powershell_package_spec.rb b/spec/unit/resource/powershell_package_spec.rb
index ff4aa991a7..d82121a97b 100644
--- a/spec/unit/resource/powershell_package_spec.rb
+++ b/spec/unit/resource/powershell_package_spec.rb
@@ -22,47 +22,77 @@ describe Chef::Resource::PowershellPackage do
let(:resource) { Chef::Resource::PowershellPackage.new("test_package") }
- it "should create a new Chef::Resource::PowershellPackage" do
- expect(resource).to be_a_kind_of(Chef::Resource)
+ it "is a subclass of Chef::Resource::Package" do
expect(resource).to be_a_kind_of(Chef::Resource::Package)
- expect(resource).to be_a_instance_of(Chef::Resource::PowershellPackage)
end
- #to check the value of resource.resource_name
- it "should have a resource name of :python" do
+ # to check the value of resource.resource_name
+ it "has a resource name of :powershell_package" do
expect(resource.resource_name).to eql(:powershell_package)
end
- it "should coerce its name to a package_name array" do
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+
+ it "coerces its name to a package_name array" do
expect(resource.package_name).to eql(["test_package"])
end
- it "the package_name setter should coerce to arrays" do
+ it "the package_name setter coerces to arrays" do
resource.package_name("git")
expect(resource.package_name).to eql(["git"])
end
- it "the package_name setter should accept arrays" do
+ it "the package_name setter accepts arrays" do
resource.package_name(%w{git unzip})
expect(resource.package_name).to eql(%w{git unzip})
end
- it "the name should accept arrays" do
+ it "the name accepts arrays" do
resource = Chef::Resource::PowershellPackage.new(%w{git unzip})
expect(resource.package_name).to eql(%w{git unzip})
end
- it "the default version should be nil" do
+ it "the default version is nil" do
expect(resource.version).to eql(nil)
end
- it "the version setter should coerce to arrays" do
+ it "the version setter coerces to arrays" do
resource.version("1.2.3")
expect(resource.version).to eql(["1.2.3"])
end
- it "the version setter should accept arrays" do
+ it "the version setter accepts arrays" do
resource.version(["1.2.3", "4.5.6"])
expect(resource.version).to eql(["1.2.3", "4.5.6"])
end
+
+ it "the default source is nil" do
+ expect(resource.source).to eql(nil)
+ end
+
+ it "the source setter accepts strings" do
+ resource.source("MyGallery")
+ expect(resource.source).to eql("MyGallery")
+ end
+
+ it "the skip_publisher_check default is false" do
+ expect(resource.skip_publisher_check).to eql(false)
+ end
+
+ it "the skip_publisher_check setter accepts booleans" do
+ resource.skip_publisher_check(true)
+ expect(resource.skip_publisher_check).to eql(true)
+ end
end
diff --git a/spec/unit/resource/powershell_script_spec.rb b/spec/unit/resource/powershell_script_spec.rb
index 9cdb6fdbee..9afd202f91 100644
--- a/spec/unit/resource/powershell_script_spec.rb
+++ b/spec/unit/resource/powershell_script_spec.rb
@@ -87,7 +87,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 +98,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..c773fd2394 100644
--- a/spec/unit/resource/python_spec.rb
+++ b/spec/unit/resource/python_spec.rb
@@ -20,21 +20,21 @@ require "spec_helper"
describe Chef::Resource::Python do
- before(:each) do
- @resource = Chef::Resource::Python.new("fakey_fakerton")
- end
+ let(:resource) { Chef::Resource::Python.new("fakey_fakerton") }
- it "should create a new Chef::Resource::Python" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Python)
+ it "has a resource name of :python" do
+ expect(resource.resource_name).to eql(:python)
end
- it "should have a resource name of :python" do
- expect(@resource.resource_name).to eql(:python)
+ it "has an interpreter of python" do
+ expect(resource.interpreter).to eql("python")
end
- it "should have an interpreter of python" do
- expect(@resource.interpreter).to eql("python")
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/reboot_spec.rb b/spec/unit/resource/reboot_spec.rb
new file mode 100644
index 0000000000..991ceec984
--- /dev/null
+++ b/spec/unit/resource/reboot_spec.rb
@@ -0,0 +1,47 @@
+#
+# Copyright:: Copyright 2017, Chef Software Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::Reboot do
+
+ let(:resource) { Chef::Resource::Reboot.new("reboot me!") }
+
+ it "sets the default action as :nothing" do
+ expect(resource.action).to eql([:nothing])
+ end
+
+ it "supports :cancel, :reboot_now, :request_reboot actions" do
+ expect { resource.action :cancel }.not_to raise_error
+ expect { resource.action :reboot_now }.not_to raise_error
+ expect { resource.action :request_reboot }.not_to raise_error
+ end
+
+ it "has a resource_name of :reboot" do
+ expect(resource.resource_name).to eq(:reboot)
+ end
+
+ it "accepts a String for the reboot reason" do
+ resource.reason "reasons"
+ expect(resource.reason).to eq("reasons")
+ end
+
+ it "accepts an Integer for delay_mins" do
+ resource.delay_mins 100
+ expect { resource.delay_mins "100" }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/registry_key_spec.rb b/spec/unit/resource/registry_key_spec.rb
index 067f2da36a..147bc8492c 100644
--- a/spec/unit/resource/registry_key_spec.rb
+++ b/spec/unit/resource/registry_key_spec.rb
@@ -19,197 +19,193 @@
require "spec_helper"
describe Chef::Resource::RegistryKey, "initialize" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
+
+ it "sets the resource_name to :registry_key" do
+ expect(resource.resource_name).to eql(:registry_key)
end
- it "should create a new Chef::Resource::RegistryKey" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::RegistryKey)
+ it "the key property is the name_property" do
+ expect(resource.key).to eql('HKCU\Software\Raxicoricofallapatorius')
end
- it "should set the resource_name to :registry_key" do
- expect(@resource.resource_name).to eql(:registry_key)
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should set the key equal to the argument to initialize" do
- expect(@resource.key).to eql('HKCU\Software\Raxicoricofallapatorius')
+ it "supports :create, :create_if_missing, :delete, :delete_key actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :delete_key }.not_to raise_error
end
- it "should default recursive to false" do
- expect(@resource.recursive).to eql(false)
+ it "defaults recursive to false" do
+ expect(resource.recursive).to eql(false)
end
- it "should default architecture to :machine" do
- expect(@resource.architecture).to eql(:machine)
+ it "defaults architecture to :machine" do
+ expect(resource.architecture).to eql(:machine)
end
- it "should set action to :create" do
- expect(@resource.action).to eql([:create])
+ it "sets action to :create" do
+ expect(resource.action).to eql([:create])
end
%w{create create_if_missing delete delete_key}.each do |action|
- it "should allow action #{action}" do
- expect(@resource.allowed_actions.detect { |a| a == action.to_sym }).to eql(action.to_sym)
+ it "allows action #{action}" do
+ expect(resource.allowed_actions.detect { |a| a == action.to_sym }).to eql(action.to_sym)
end
end
end
describe Chef::Resource::RegistryKey, "key" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- it "should allow a string" do
- @resource.key 'HKCU\Software\Poosh'
- expect(@resource.key).to eql('HKCU\Software\Poosh')
+ it "allows a string" do
+ resource.key 'HKCU\Software\Poosh'
+ expect(resource.key).to eql('HKCU\Software\Poosh')
end
- it "should not allow an integer" do
- expect { @resource.send(:key, 100) }.to raise_error(ArgumentError)
+ it "does not allow an integer" do
+ expect { resource.send(:key, 100) }.to raise_error(ArgumentError)
end
- it "should not allow a hash" do
- expect { @resource.send(:key, { :sonic => "screwdriver" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(:key, { sonic: "screwdriver" }) }.to raise_error(ArgumentError)
end
end
describe Chef::Resource::RegistryKey, "values" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- it "should allow a single proper hash of registry values" do
- @resource.values( { :name => "poosh", :type => :string, :data => "carmen" } )
- expect(@resource.values).to eql([ { :name => "poosh", :type => :string, :data => "carmen" } ])
+ it "allows a single proper hash of registry values" do
+ resource.values( { name: "poosh", type: :string, data: "carmen" } )
+ expect(resource.values).to eql([ { name: "poosh", type: :string, data: "carmen" } ])
end
- it "should allow an array of proper hashes of registry values" do
- @resource.values [ { :name => "poosh", :type => :string, :data => "carmen" } ]
- expect(@resource.values).to eql([ { :name => "poosh", :type => :string, :data => "carmen" } ])
+ it "allows an array of proper hashes of registry values" do
+ resource.values [ { name: "poosh", type: :string, data: "carmen" } ]
+ expect(resource.values).to eql([ { name: "poosh", type: :string, data: "carmen" } ])
end
- it "should return checksummed data if the type is unsafe" do
- @resource.values( { :name => "poosh", :type => :binary, :data => 255.chr * 1 })
- expect(@resource.values).to eql([ { :name => "poosh", :type => :binary, :data => "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89" } ])
+ it "returns checksummed data if the type is unsafe" do
+ resource.values( { name: "poosh", type: :binary, data: 255.chr * 1 })
+ expect(resource.values).to eql([ { name: "poosh", type: :binary, data: "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89" } ])
end
- it "should raise an exception if the name field is missing" do
- expect { @resource.values [ { :type => :string, :data => "carmen" } ] }.to raise_error(ArgumentError)
+ it "raises an exception if the name field is missing" do
+ expect { resource.values [ { type: :string, data: "carmen" } ] }.to raise_error(ArgumentError)
end
- it "should raise an exception if extra fields are present" do
- expect { @resource.values [ { :name => "poosh", :type => :string, :data => "carmen", :screwdriver => "sonic" } ] }.to raise_error(ArgumentError)
+ it "raises an exception if extra fields are present" do
+ expect { resource.values [ { name: "poosh", type: :string, data: "carmen", screwdriver: "sonic" } ] }.to raise_error(ArgumentError)
end
- it "should not allow a string" do
- expect { @resource.send(:values, "souffle") }.to raise_error(ArgumentError)
+ it "does not allow a string" do
+ expect { resource.send(:values, "souffle") }.to raise_error(ArgumentError)
end
- it "should not allow an integer" do
- expect { @resource.send(:values, 100) }.to raise_error(ArgumentError)
+ it "does not allow an integer" do
+ expect { resource.send(:values, 100) }.to raise_error(ArgumentError)
end
- it "should raise an exception if type of name is not string" do
- expect { @resource.values([ { :name => 123, :type => :string, :data => "carmen" } ]) }.to raise_error(ArgumentError)
+ it "raises an exception if type of name is not string" do
+ expect { resource.values([ { name: 123, type: :string, data: "carmen" } ]) }.to raise_error(ArgumentError)
end
- it "should not raise an exception if type of name is string" do
- expect { @resource.values([ { :name => "123", :type => :string, :data => "carmen" } ]) }.to_not raise_error
+ it "does not raise an exception if type of name is string" do
+ expect { resource.values([ { name: "123", type: :string, data: "carmen" } ]) }.to_not raise_error
end
context "type key not given" do
- it "should not raise an exception" do
- expect { @resource.values([ { :name => "123", :data => "carmen" } ]) }.to_not raise_error
+ it "does not raise an exception" do
+ expect { resource.values([ { name: "123", data: "carmen" } ]) }.to_not raise_error
end
end
context "type key given" do
- it "should raise an exception if type of type is not symbol" do
- expect { @resource.values([ { :name => "123", :type => "string", :data => "carmen" } ]) }.to raise_error(ArgumentError)
+ it "raises an exception if type of type is not symbol" do
+ expect { resource.values([ { name: "123", type: "string", data: "carmen" } ]) }.to raise_error(ArgumentError)
end
- it "should not raise an exception if type of type is symbol" do
- expect { @resource.values([ { :name => "123", :type => :string, :data => "carmen" } ]) }.to_not raise_error
+ it "does not raise an exception if type of type is symbol" do
+ expect { resource.values([ { name: "123", type: :string, data: "carmen" } ]) }.to_not raise_error
end
end
end
describe Chef::Resource::RegistryKey, "recursive" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- it "should allow a boolean" do
- @resource.recursive(true)
- expect(@resource.recursive).to eql(true)
+ it "allows a boolean" do
+ resource.recursive(true)
+ expect(resource.recursive).to eql(true)
end
- it "should not allow a hash" do
- expect { @resource.recursive({ :sonic => :screwdriver }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.recursive({ sonic: :screwdriver }) }.to raise_error(ArgumentError)
end
- it "should not allow an array" do
- expect { @resource.recursive([:nose, :chin]) }.to raise_error(ArgumentError)
+ it "does not allow an array" do
+ expect { resource.recursive([:nose, :chin]) }.to raise_error(ArgumentError)
end
- it "should not allow a string" do
- expect { @resource.recursive("souffle") }.to raise_error(ArgumentError)
+ it "does not allow a string" do
+ expect { resource.recursive("souffle") }.to raise_error(ArgumentError)
end
- it "should not allow an integer" do
- expect { @resource.recursive(100) }.to raise_error(ArgumentError)
+ it "does not allow an integer" do
+ expect { resource.recursive(100) }.to raise_error(ArgumentError)
end
end
describe Chef::Resource::RegistryKey, "architecture" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
[ :i386, :x86_64, :machine ].each do |arch|
- it "should allow #{arch} as a symbol" do
- @resource.architecture(arch)
- expect(@resource.architecture).to eql(arch)
+ it "allows #{arch} as a symbol" do
+ resource.architecture(arch)
+ expect(resource.architecture).to eql(arch)
end
end
- it "should not allow a hash" do
- expect { @resource.architecture({ :sonic => :screwdriver }) }.to raise_error(ArgumentError)
+ it "does not allow other symbols" do
+ expect { resource.architecture(:nope) }.to raise_error(ArgumentError)
end
- it "should not allow an array" do
- expect { @resource.architecture([:nose, :chin]) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.architecture({ sonic: :screwdriver }) }.to raise_error(ArgumentError)
end
- it "should not allow a string" do
- expect { @resource.architecture("souffle") }.to raise_error(ArgumentError)
+ it "does not allow an array" do
+ expect { resource.architecture([:nose, :chin]) }.to raise_error(ArgumentError)
end
- it "should not allow an integer" do
- expect { @resource.architecture(100) }.to raise_error(ArgumentError)
+ it "does not allow a string" do
+ expect { resource.architecture("souffle") }.to raise_error(ArgumentError)
+ end
+
+ it "does not allow an integer" do
+ expect { resource.architecture(100) }.to raise_error(ArgumentError)
end
end
describe Chef::Resource::RegistryKey, ":unscrubbed_values" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- it "should return unsafe data as-is" do
- key_values = [ { :name => "poosh", :type => :binary, :data => 255.chr * 1 } ]
- @resource.values(key_values)
- expect(@resource.unscrubbed_values).to eql(key_values)
+ it "returns unsafe data as-is" do
+ key_values = [ { name: "poosh", type: :binary, data: 255.chr * 1 } ]
+ resource.values(key_values)
+ expect(resource.unscrubbed_values).to eql(key_values)
end
end
describe Chef::Resource::RegistryKey, "state" do
- before(:each) do
- @resource = Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius')
- end
+ let(:resource) { Chef::Resource::RegistryKey.new('HKCU\Software\Raxicoricofallapatorius') }
- it "should return scrubbed values" do
- @resource.values([ { :name => "poosh", :type => :binary, :data => 255.chr * 1 } ])
- expect(@resource.state_for_resource_reporter).to eql( { :values => [{ :name => "poosh", :type => :binary, :data => "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89" }] } )
+ it "returns scrubbed values" do
+ resource.values([ { name: "poosh", type: :binary, data: 255.chr * 1 } ])
+ expect(resource.state_for_resource_reporter[:values]).to eql( [{ 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 370b8d8225..f010ebdf96 100644
--- a/spec/unit/resource/remote_directory_spec.rb
+++ b/spec/unit/resource/remote_directory_spec.rb
@@ -20,78 +20,86 @@ require "spec_helper"
describe Chef::Resource::RemoteDirectory do
- before(:each) do
- @resource = Chef::Resource::RemoteDirectory.new("/etc/dunk")
+ let(:resource) { Chef::Resource::RemoteDirectory.new("/etc/dunk") }
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("/etc/dunk")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
end
- it "should create a new Chef::Resource::RemoteDirectory" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::RemoteDirectory)
+ it "supports :create, :create_if_missing, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
end
- it "should set the path to the first argument to new" do
- expect(@resource.path).to eql("/etc/dunk")
+ it "accepts a string for the remote directory source" do
+ resource.source "foo"
+ expect(resource.source).to eql("foo")
end
- it "should accept a string for the remote directory source" do
- @resource.source "foo"
- expect(@resource.source).to eql("foo")
+ it "has the basename of the remote directory resource as the default source" do
+ resource.path "/foo/bar"
+ expect(resource.source).to eql("bar")
end
- it "should have the basename of the remote directory resource as the default source" do
- expect(@resource.source).to eql("dunk")
+ it "accepts a number for the remote files backup" do
+ resource.files_backup 1
+ expect(resource.files_backup).to eql(1)
end
- it "should accept a number for the remote files backup" do
- @resource.files_backup 1
- expect(@resource.files_backup).to eql(1)
+ it "accepts false for the remote files backup" do
+ resource.files_backup false
+ expect(resource.files_backup).to eql(false)
end
- it "should accept false for the remote files backup" do
- @resource.files_backup false
- expect(@resource.files_backup).to eql(false)
+ it "accepts 3 or 4 digits for the files_mode" do
+ resource.files_mode 100
+ expect(resource.files_mode).to eql(100)
+ resource.files_mode 1000
+ expect(resource.files_mode).to eql(1000)
end
- it "should accept 3 or 4 digets for the files_mode" do
- @resource.files_mode 100
- expect(@resource.files_mode).to eql(100)
- @resource.files_mode 1000
- expect(@resource.files_mode).to eql(1000)
+ it "accepts a string or number for the files group" do
+ resource.files_group "heart"
+ expect(resource.files_group).to eql("heart")
+ resource.files_group 1000
+ expect(resource.files_group).to eql(1000)
end
- it "should accept a string or number for the files group" do
- @resource.files_group "heart"
- expect(@resource.files_group).to eql("heart")
- @resource.files_group 1000
- expect(@resource.files_group).to eql(1000)
+ it "accepts a string or number for the files owner" do
+ resource.files_owner "heart"
+ expect(resource.files_owner).to eql("heart")
+ resource.files_owner 1000
+ expect(resource.files_owner).to eql(1000)
end
- it "should accept a string or number for the files owner" do
- @resource.files_owner "heart"
- expect(@resource.files_owner).to eql("heart")
- @resource.files_owner 1000
- expect(@resource.files_owner).to eql(1000)
+ it "overwrites by default" do
+ expect(resource.overwrite).to be true
end
describe "when it has cookbook, files owner, files mode, and source" do
before do
- @resource.path("/var/path/")
- @resource.cookbook("pokemon.rb")
- @resource.files_owner("root")
- @resource.files_group("supergroup")
- @resource.files_mode("0664")
- @resource.source("/var/source/")
+ resource.path("/var/path/")
+ resource.cookbook("pokemon.rb")
+ resource.files_owner("root")
+ resource.files_group("supergroup")
+ resource.files_mode("0664")
+ resource.source("/var/source/")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:files_owner]).to eq("root")
expect(state[:files_group]).to eq("supergroup")
expect(state[:files_mode]).to eq("0664")
end
it "returns the path as its identity" do
- expect(@resource.identity).to eq("/var/path/")
+ expect(resource.identity).to eq("/var/path/")
end
end
end
diff --git a/spec/unit/resource/remote_file_spec.rb b/spec/unit/resource/remote_file_spec.rb
index eca3db3420..39d34d9a96 100644
--- a/spec/unit/resource/remote_file_spec.rb
+++ b/spec/unit/resource/remote_file_spec.rb
@@ -21,147 +21,160 @@ require "spec_helper"
describe Chef::Resource::RemoteFile do
- before(:each) do
- @resource = Chef::Resource::RemoteFile.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::RemoteFile.new("fakey_fakerton") }
+
+ describe "name_property" do
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
+ end
+ end
+
+ describe "Actions" do
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :create_if_missing, :delete, :touch actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :touch }.not_to raise_error
+ end
end
describe "initialize" do
- it "should create a new Chef::Resource::RemoteFile" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::File)
- expect(@resource).to be_a_kind_of(Chef::Resource::RemoteFile)
+ it "is a subclass of Chef::Resource::File" do
+ expect(resource).to be_a_kind_of(Chef::Resource::File)
end
end
it "says its provider is RemoteFile when the source is an absolute URI" do
- @resource.source("http://www.google.com/robots.txt")
- expect(@resource.provider).to eq(Chef::Provider::RemoteFile)
- expect(@resource.provider_for_action(:create)).to be_kind_of(Chef::Provider::RemoteFile)
+ resource.source("http://www.google.com/robots.txt")
+ expect(resource.provider_for_action(:create)).to be_kind_of(Chef::Provider::RemoteFile)
end
it "says its provider is RemoteFile when the source is a network share" do
- @resource.source("\\\\fakey\\fakerton\\fake.txt")
- expect(@resource.provider).to eq(Chef::Provider::RemoteFile)
- expect(@resource.provider_for_action(:create)).to be_kind_of(Chef::Provider::RemoteFile)
+ resource.source("\\\\fakey\\fakerton\\fake.txt")
+ expect(resource.provider_for_action(:create)).to be_kind_of(Chef::Provider::RemoteFile)
end
describe "source" do
it "does not have a default value for 'source'" do
- expect(@resource.source).to eql([])
+ expect(resource.source).to eql([])
end
- it "should accept a URI for the remote file source" do
- @resource.source "http://opscode.com/"
- expect(@resource.source).to eql([ "http://opscode.com/" ])
+ it "accepts a URI for the remote file source" do
+ resource.source "http://opscode.com/"
+ expect(resource.source).to eql([ "http://opscode.com/" ])
end
- it "should accept a windows network share source" do
- @resource.source "\\\\fakey\\fakerton\\fake.txt"
- expect(@resource.source).to eql([ "\\\\fakey\\fakerton\\fake.txt" ])
+ it "accepts a windows network share source" do
+ resource.source "\\\\fakey\\fakerton\\fake.txt"
+ expect(resource.source).to eql([ "\\\\fakey\\fakerton\\fake.txt" ])
end
- it "should accept file URIs with spaces" do
- @resource.source("file:///C:/foo bar")
- expect(@resource.source).to eql(["file:///C:/foo bar"])
+ it "accepts file URIs with spaces" do
+ resource.source("file:///C:/foo bar")
+ expect(resource.source).to eql(["file:///C:/foo bar"])
end
- it "should accept a delayed evalutator (string) for the remote file source" do
- @resource.source Chef::DelayedEvaluator.new { "http://opscode.com/" }
- expect(@resource.source).to eql([ "http://opscode.com/" ])
+ it "accepts a delayed evalutator (string) for the remote file source" do
+ resource.source Chef::DelayedEvaluator.new { "http://opscode.com/" }
+ expect(resource.source).to eql([ "http://opscode.com/" ])
end
- it "should accept an array of URIs for the remote file source" do
- @resource.source([ "http://opscode.com/", "http://puppetlabs.com/" ])
- expect(@resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
+ it "accepts an array of URIs for the remote file source" do
+ resource.source([ "http://opscode.com/", "http://puppetlabs.com/" ])
+ expect(resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
end
- it "should accept a delated evaluator (array) for the remote file source" do
- @resource.source Chef::DelayedEvaluator.new { [ "http://opscode.com/", "http://puppetlabs.com/" ] }
- expect(@resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
+ it "accepts a delated evaluator (array) for the remote file source" do
+ resource.source Chef::DelayedEvaluator.new { [ "http://opscode.com/", "http://puppetlabs.com/" ] }
+ expect(resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
end
- it "should accept an multiple URIs as arguments for the remote file source" do
- @resource.source("http://opscode.com/", "http://puppetlabs.com/")
- expect(@resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
+ it "accepts an multiple URIs as arguments for the remote file source" do
+ resource.source("http://opscode.com/", "http://puppetlabs.com/")
+ expect(resource.source).to eql([ "http://opscode.com/", "http://puppetlabs.com/" ])
end
- it "should only accept a single argument if a delayed evalutor is used" do
+ it "only accept a single argument if a delayed evalutor is used" do
expect do
- @resource.source("http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" })
+ resource.source("http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" })
end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI)
end
- it "should only accept a single array item if a delayed evalutor is used" do
+ it "only accept a single array item if a delayed evalutor is used" do
expect do
- @resource.source(["http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }])
+ resource.source(["http://opscode.com/", Chef::DelayedEvaluator.new { "http://opscode.com/" }])
end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI)
end
it "does not accept a non-URI as the source" do
- expect { @resource.source("not-a-uri") }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI)
+ expect { resource.source("not-a-uri") }.to raise_error(Chef::Exceptions::InvalidRemoteFileURI)
end
it "does not accept a non-URI as the source when read from a delayed evaluator" do
expect do
- @resource.source(Chef::DelayedEvaluator.new { "not-a-uri" })
- @resource.source
+ resource.source(Chef::DelayedEvaluator.new { "not-a-uri" })
+ resource.source
end.to raise_error(Chef::Exceptions::InvalidRemoteFileURI)
end
- it "should raise an exception when source is an empty array" do
- expect { @resource.source([]) }.to raise_error(ArgumentError)
+ it "raises an exception when source is an empty array" do
+ expect { resource.source([]) }.to raise_error(ArgumentError)
end
end
describe "checksum" do
- it "should accept a string for the checksum object" do
- @resource.checksum "asdf"
- expect(@resource.checksum).to eql("asdf")
+ it "accepts a string for the checksum object" do
+ resource.checksum "asdf"
+ expect(resource.checksum).to eql("asdf")
end
- it "should default to nil" do
- expect(@resource.checksum).to eq(nil)
+ it "defaults to nil" do
+ expect(resource.checksum).to eq(nil)
end
end
describe "ftp_active_mode" do
- it "should accept a boolean for the ftp_active_mode object" do
- @resource.ftp_active_mode true
- expect(@resource.ftp_active_mode).to be_truthy
+ it "accepts a boolean for the ftp_active_mode object" do
+ resource.ftp_active_mode true
+ expect(resource.ftp_active_mode).to be_truthy
end
- it "should default to false" do
- expect(@resource.ftp_active_mode).to be_falsey
+ it "defaults to false" do
+ expect(resource.ftp_active_mode).to be_falsey
end
end
describe "conditional get options" do
it "defaults to using etags and last modified" do
- expect(@resource.use_etags).to be_truthy
- expect(@resource.use_last_modified).to be_truthy
+ expect(resource.use_etags).to be_truthy
+ expect(resource.use_last_modified).to be_truthy
end
it "enable or disables etag and last modified options as a group" do
- @resource.use_conditional_get(false)
- expect(@resource.use_etags).to be_falsey
- expect(@resource.use_last_modified).to be_falsey
+ resource.use_conditional_get(false)
+ expect(resource.use_etags).to be_falsey
+ expect(resource.use_last_modified).to be_falsey
- @resource.use_conditional_get(true)
- expect(@resource.use_etags).to be_truthy
- expect(@resource.use_last_modified).to be_truthy
+ resource.use_conditional_get(true)
+ expect(resource.use_etags).to be_truthy
+ expect(resource.use_last_modified).to be_truthy
end
it "disables etags indivdually" do
- @resource.use_etags(false)
- expect(@resource.use_etags).to be_falsey
- expect(@resource.use_last_modified).to be_truthy
+ resource.use_etags(false)
+ expect(resource.use_etags).to be_falsey
+ expect(resource.use_last_modified).to be_truthy
end
it "disables last modified individually" do
- @resource.use_last_modified(false)
- expect(@resource.use_last_modified).to be_falsey
- expect(@resource.use_etags).to be_truthy
+ resource.use_last_modified(false)
+ expect(resource.use_last_modified).to be_falsey
+ expect(resource.use_etags).to be_truthy
end
end
@@ -169,25 +182,25 @@ describe Chef::Resource::RemoteFile do
describe "when it has group, mode, owner, source, and checksum" do
before do
if Chef::Platform.windows?
- @resource.path("C:/temp/origin/file.txt")
- @resource.rights(:read, "Everyone")
- @resource.deny_rights(:full_control, "Clumsy_Sam")
+ resource.path("C:/temp/origin/file.txt")
+ resource.rights(:read, "Everyone")
+ resource.deny_rights(:full_control, "Clumsy_Sam")
else
- @resource.path("/this/path/")
- @resource.group("pokemon")
- @resource.mode("0664")
- @resource.owner("root")
+ resource.path("/this/path/")
+ resource.group("pokemon")
+ resource.mode("0664")
+ resource.owner("root")
end
- @resource.source("https://www.google.com/images/srpr/logo3w.png")
- @resource.checksum("1" * 26)
+ resource.source("https://www.google.com/images/srpr/logo3w.png")
+ resource.checksum("1" * 26)
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
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")
@@ -198,9 +211,9 @@ describe Chef::Resource::RemoteFile do
it "returns the path as its identity" do
if Chef::Platform.windows?
- expect(@resource.identity).to eq("C:/temp/origin/file.txt")
+ expect(resource.identity).to eq("C:/temp/origin/file.txt")
else
- expect(@resource.identity).to eq("/this/path/")
+ expect(resource.identity).to eq("/this/path/")
end
end
end
diff --git a/spec/unit/resource/resource_notification_spec.rb b/spec/unit/resource/resource_notification_spec.rb
index e141e01fcf..07fd63bb2b 100644
--- a/spec/unit/resource/resource_notification_spec.rb
+++ b/spec/unit/resource/resource_notification_spec.rb
@@ -65,7 +65,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 +78,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 +87,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 +100,7 @@ describe Chef::Resource::Notification do
end
it "raises a RuntimeError if you try to reference multiple resources" do
- notification.resource = { :cat => %w{keyboard_cat cheez_cat} }
+ notification.resource = { cat: %w{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
@@ -112,7 +112,7 @@ describe Chef::Resource::Notification do
end
it "raises a RuntimeError if you try to reference multiple notifying resources" do
- notification.notifying_resource = { :cat => %w{long_cat cheez_cat} }
+ notification.notifying_resource = { cat: %w{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
@@ -124,7 +124,7 @@ describe Chef::Resource::Notification do
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
@@ -134,7 +134,7 @@ describe Chef::Resource::Notification do
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
diff --git a/spec/unit/resource/rhsm_errata_level_spec.rb b/spec/unit/resource/rhsm_errata_level_spec.rb
new file mode 100644
index 0000000000..8d0de18f98
--- /dev/null
+++ b/spec/unit/resource/rhsm_errata_level_spec.rb
@@ -0,0 +1,50 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::RhsmErrataLevel do
+
+ let(:resource) { Chef::Resource::RhsmErrataLevel.new("moderate") }
+
+ it "has a resource name of :rhsm_errata_level" do
+ expect(resource.resource_name).to eql(:rhsm_errata_level)
+ end
+
+ it "the errata_level property is the name_property" do
+ expect(resource.errata_level).to eql("moderate")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install action" do
+ expect { resource.action :install }.not_to raise_error
+ end
+
+ it "coerces the errata_level to be lowercase" do
+ resource.errata_level "Important"
+ expect(resource.errata_level).to eql("important")
+ end
+
+ it "raises an exception if invalid errata_level is passed" do
+ expect do
+ resource.errata_level "FOO"
+ end.to raise_error(Chef::Exceptions::ValidationFailed)
+ end
+end
diff --git a/spec/unit/resource/rhsm_errata_spec.rb b/spec/unit/resource/rhsm_errata_spec.rb
new file mode 100644
index 0000000000..4d708bff5d
--- /dev/null
+++ b/spec/unit/resource/rhsm_errata_spec.rb
@@ -0,0 +1,39 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::RhsmErrata do
+
+ let(:resource) { Chef::Resource::RhsmErrata.new("fakey_fakerton") }
+
+ it "has a resource name of :rhsm_errata" do
+ expect(resource.resource_name).to eql(:rhsm_errata)
+ end
+
+ it "the errata_id property is the name_property" do
+ expect(resource.errata_id).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install action" do
+ expect { resource.action :install }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/rhsm_register_spec.rb b/spec/unit/resource/rhsm_register_spec.rb
new file mode 100644
index 0000000000..3c39bba131
--- /dev/null
+++ b/spec/unit/resource/rhsm_register_spec.rb
@@ -0,0 +1,204 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::RhsmRegister do
+
+ let(:resource) { Chef::Resource::RhsmRegister.new("foo") }
+ let(:provider) { resource.provider_for_action(:register) }
+
+ it "has a resource name of :rhsm_register" do
+ expect(resource.resource_name).to eql(:rhsm_register)
+ end
+
+ it "sets the default action as :register" do
+ expect(resource.action).to eql([:register])
+ end
+
+ it "supports :register, :unregister actions" do
+ expect { resource.action :register }.not_to raise_error
+ expect { resource.action :unregister }.not_to raise_error
+ end
+
+ it "coerces activation_key to an array" do
+ resource.activation_key "foo"
+ expect(resource.activation_key).to eql(["foo"])
+ end
+
+ describe "#katello_cert_rpm_installed?" do
+ let(:cmd) { double("cmd") }
+
+ before do
+ allow(Mixlib::ShellOut).to receive(:new).and_return(cmd)
+ allow(cmd).to receive(:run_command)
+ end
+
+ context "when the output contains katello-ca-consumer" do
+ it "returns true" do
+ allow(cmd).to receive(:stdout).and_return("katello-ca-consumer-somehostname-1.0-1")
+ expect(provider.katello_cert_rpm_installed?).to eq(true)
+ end
+ end
+
+ context "when the output does not contain katello-ca-consumer" do
+ it "returns false" do
+ allow(cmd).to receive(:stdout).and_return("katello-agent-but-not-the-ca")
+ expect(provider.katello_cert_rpm_installed?).to eq(false)
+ end
+ end
+ end
+
+ describe "#register_command" do
+ before do
+ allow(provider).to receive(:activation_key).and_return([])
+ allow(provider).to receive(:auto_attach)
+ end
+
+ context "when activation keys exist" do
+ before do
+ allow(resource).to receive(:activation_key).and_return(%w{key1 key2})
+ end
+
+ context "when no org exists" do
+ it "raises an exception" do
+ allow(resource).to receive(:organization).and_return(nil)
+ expect { provider.register_command }.to raise_error(RuntimeError)
+ end
+ end
+
+ context "when an org exists" do
+ it "returns a command containing the keys and org" do
+ allow(resource).to receive(:organization).and_return("myorg")
+
+ expect(provider.register_command).to match("--activationkey=key1 --activationkey=key2 --org=myorg")
+ end
+ end
+
+ context "when auto_attach is true" do
+ it "does not return a command with --auto-attach since it is not supported with activation keys" do
+ allow(resource).to receive(:organization).and_return("myorg")
+ allow(resource).to receive(:auto_attach).and_return(true)
+
+ expect(provider.register_command).not_to match("--auto-attach")
+ end
+ end
+ end
+
+ context "when username and password exist" do
+ before do
+ allow(resource).to receive(:username).and_return("myuser")
+ allow(resource).to receive(:password).and_return("mypass")
+ allow(resource).to receive(:environment)
+ allow(resource).to receive(:using_satellite_host?)
+ allow(resource).to receive(:activation_key).and_return([])
+ end
+
+ context "when auto_attach is true" do
+ it "returns a command containing --auto-attach" do
+ allow(resource).to receive(:auto_attach).and_return(true)
+
+ expect(provider.register_command).to match("--auto-attach")
+ end
+ end
+
+ context "when auto_attach is false" do
+ it "returns a command that does not contain --auto-attach" do
+ allow(resource).to receive(:auto_attach).and_return(false)
+
+ expect(provider.register_command).not_to match("--auto-attach")
+ end
+ end
+
+ context "when auto_attach is nil" do
+ it "returns a command that does not contain --auto-attach" do
+ allow(resource).to receive(:auto_attach).and_return(nil)
+
+ expect(provider.register_command).not_to match("--auto-attach")
+ end
+ end
+
+ context "when environment does not exist" do
+ context "when registering to a satellite server" do
+ it "raises an exception" do
+ allow(provider).to receive(:using_satellite_host?).and_return(true)
+ allow(resource).to receive(:environment).and_return(nil)
+ expect { provider.register_command }.to raise_error(RuntimeError)
+ end
+ end
+
+ context "when registering to RHSM proper" do
+ before do
+ allow(provider).to receive(:using_satellite_host?).and_return(false)
+ allow(resource).to receive(:environment).and_return(nil)
+ end
+
+ it "does not raise an exception" do
+ expect { provider.register_command }.not_to raise_error
+ end
+
+ it "returns a command containing the username and password and no environment" do
+ allow(resource).to receive(:environment).and_return("myenv")
+ expect(provider.register_command).to match("--username=myuser --password=mypass")
+ expect(provider.register_command).not_to match("--environment")
+ end
+ end
+ end
+
+ context "when an environment exists" do
+ it "returns a command containing the username, password, and environment" do
+ allow(provider).to receive(:using_satellite_host?).and_return(true)
+ allow(resource).to receive(:environment).and_return("myenv")
+ expect(provider.register_command).to match("--username=myuser --password=mypass --environment=myenv")
+ end
+ end
+ end
+
+ context "when no activation keys, username, or password exist" do
+ it "raises an exception" do
+ allow(resource).to receive(:activation_key).and_return([])
+ allow(resource).to receive(:username).and_return(nil)
+ allow(resource).to receive(:password).and_return(nil)
+
+ expect { provider.register_command }.to raise_error(RuntimeError)
+ end
+ end
+ end
+
+ describe "#registered_with_rhsm?" do
+ let(:cmd) { double("cmd") }
+
+ before do
+ allow(Mixlib::ShellOut).to receive(:new).and_return(cmd)
+ allow(cmd).to receive(:run_command)
+ end
+
+ context "when the status is Unknown" do
+ it "returns false" do
+ allow(cmd).to receive(:stdout).and_return("Overall Status: Unknown")
+ expect(provider.registered_with_rhsm?).to eq(false)
+ end
+ end
+
+ context "when the status is anything else" do
+ it "returns true" do
+ allow(cmd).to receive(:stdout).and_return("Overall Status: Insufficient")
+ expect(provider.registered_with_rhsm?).to eq(true)
+ end
+ end
+ end
+end
diff --git a/spec/unit/resource/rhsm_repo_spec.rb b/spec/unit/resource/rhsm_repo_spec.rb
new file mode 100644
index 0000000000..36eb235798
--- /dev/null
+++ b/spec/unit/resource/rhsm_repo_spec.rb
@@ -0,0 +1,64 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::RhsmRepo do
+
+ let(:resource) { Chef::Resource::RhsmRepo.new("fakey_fakerton") }
+ let(:provider) { resource.provider_for_action(:enable) }
+
+ it "has a resource name of :rhsm_repo" do
+ expect(resource.resource_name).to eql(:rhsm_repo)
+ end
+
+ it "the repo_name property is the name_property" do
+ expect(resource.repo_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :enable" do
+ expect(resource.action).to eql([:enable])
+ end
+
+ it "supports :disable, :enable actions" do
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ end
+
+ describe "#repo_enabled?" do
+ let(:cmd) { double("cmd") }
+ let(:output) { "Repo ID: repo123" }
+
+ before do
+ allow(Mixlib::ShellOut).to receive(:new).and_return(cmd)
+ allow(cmd).to receive(:run_command)
+ allow(cmd).to receive(:stdout).and_return(output)
+ end
+
+ context "when the repo provided matches the output" do
+ it "returns true" do
+ expect(provider.repo_enabled?("repo123")).to eq(true)
+ end
+ end
+
+ context "when the repo provided does not match the output" do
+ it "returns false" do
+ expect(provider.repo_enabled?("differentrepo")).to eq(false)
+ end
+ end
+ end
+end
diff --git a/spec/unit/resource/rhsm_subscription_spec.rb b/spec/unit/resource/rhsm_subscription_spec.rb
new file mode 100644
index 0000000000..6de65a427f
--- /dev/null
+++ b/spec/unit/resource/rhsm_subscription_spec.rb
@@ -0,0 +1,98 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::RhsmSubscription do
+ let(:resource) { Chef::Resource::RhsmSubscription.new("fakey_fakerton") }
+ let(:provider) { resource.provider_for_action(:attach) }
+
+ it "has a resource name of :rhsm_subscription" do
+ expect(resource.resource_name).to eql(:rhsm_subscription)
+ end
+
+ it "the pool_id property is the name_property" do
+ expect(resource.pool_id).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :attach" do
+ expect(resource.action).to eql([:attach])
+ end
+
+ it "supports :attach, :remove actions" do
+ expect { resource.action :attach }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ describe "#subscription_attached?" do
+ let(:cmd) { double("cmd") }
+ let(:output) { "Pool ID: pool123" }
+
+ before do
+ allow(Mixlib::ShellOut).to receive(:new).and_return(cmd)
+ allow(cmd).to receive(:run_command)
+ allow(cmd).to receive(:stdout).and_return(output)
+ end
+
+ context "when the pool provided matches the output" do
+ it "returns true" do
+ expect(provider.subscription_attached?("pool123")).to eq(true)
+ end
+ end
+
+ context "when the pool provided does not match the output" do
+ it "returns false" do
+ expect(provider.subscription_attached?("differentpool")).to eq(false)
+ end
+ end
+ end
+
+ describe "#serials_by_pool" do
+ let(:cmd) { double("cmd") }
+ let(:output) do
+ <<~EOL
+ Key1: value1
+ Pool ID: pool1
+ Serial: serial1
+ Key2: value2
+
+ Key1: value1
+ Pool ID: pool2
+ Serial: serial2
+ Key2: value2
+EOL
+ end
+
+ it "parses the output correctly" do
+ allow(Mixlib::ShellOut).to receive(:new).and_return(cmd)
+ allow(cmd).to receive(:run_command)
+ allow(cmd).to receive(:stdout).and_return(output)
+
+ expect(provider.serials_by_pool["pool1"]).to eq("serial1")
+ expect(provider.serials_by_pool["pool2"]).to eq("serial2")
+ end
+ end
+
+ describe "#pool_serial" do
+ let(:serials) { { "pool1" => "serial1", "pool2" => "serial2" } }
+
+ it "returns the serial for a given pool" do
+ allow(provider).to receive(:serials_by_pool).and_return(serials)
+ expect(provider.pool_serial("pool1")).to eq("serial1")
+ end
+ end
+end
diff --git a/spec/unit/resource/route_spec.rb b/spec/unit/resource/route_spec.rb
index 884b477365..d4248755b5 100644
--- a/spec/unit/resource/route_spec.rb
+++ b/spec/unit/resource/route_spec.rb
@@ -21,87 +21,75 @@ require "spec_helper"
describe Chef::Resource::Route do
- before(:each) do
- @resource = Chef::Resource::Route.new("10.0.0.10")
- end
-
- it "should create a new Chef::Resource::Route" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Route)
- end
-
- it "should have a name" do
- expect(@resource.name).to eql("10.0.0.10")
- end
+ let(:resource) { Chef::Resource::Route.new("10.0.0.10") }
- it "should have a default action of 'add'" do
- expect(@resource.action).to eql([:add])
+ it "the target property is the name_property" do
+ expect(resource.target).to eql("10.0.0.10")
end
- it "should accept add or delete for action" do
- expect { @resource.action :add }.not_to raise_error
- expect { @resource.action :delete }.not_to raise_error
- expect { @resource.action :lolcat }.to raise_error(ArgumentError)
+ it "sets the default action as :add" do
+ expect(resource.action).to eql([:add])
end
- it "should use the object name as the target by default" do
- expect(@resource.target).to eql("10.0.0.10")
+ it "supports :add, :delete actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
end
- it "should allow you to specify the netmask" do
- @resource.netmask "255.255.255.0"
- expect(@resource.netmask).to eql("255.255.255.0")
+ it "allows you to specify the netmask" do
+ resource.netmask "255.255.255.0"
+ expect(resource.netmask).to eql("255.255.255.0")
end
- it "should allow you to specify the gateway" do
- @resource.gateway "10.0.0.1"
- expect(@resource.gateway).to eql("10.0.0.1")
+ it "allows you to specify the gateway" do
+ resource.gateway "10.0.0.1"
+ expect(resource.gateway).to eql("10.0.0.1")
end
- it "should allow you to specify the metric" do
- @resource.metric 10
- expect(@resource.metric).to eql(10)
+ it "allows you to specify the metric" do
+ resource.metric 10
+ expect(resource.metric).to eql(10)
end
- it "should allow you to specify the device" do
- @resource.device "eth0"
- expect(@resource.device).to eql("eth0")
+ it "allows you to specify the device" do
+ resource.device "eth0"
+ expect(resource.device).to eql("eth0")
end
- it "should allow you to specify the route type" do
- @resource.route_type "host"
- expect(@resource.route_type).to eql(:host)
+ it "allows you to specify the route type" do
+ resource.route_type "host"
+ expect(resource.route_type).to eql(:host)
end
- it "should default to a host route type" do
- expect(@resource.route_type).to eql(:host)
+ it "defaults to a host route type" do
+ expect(resource.route_type).to eql(:host)
end
- it "should accept a net route type" do
- @resource.route_type :net
- expect(@resource.route_type).to eql(:net)
+ it "accepts a net route type" do
+ resource.route_type :net
+ expect(resource.route_type).to eql(:net)
end
- it "should reject any other route_type but :host and :net" do
- expect { @resource.route_type "lolcat" }.to raise_error(ArgumentError)
+ it "rejects any other route_type but :host and :net" do
+ expect { resource.route_type "lolcat" }.to raise_error(ArgumentError)
end
describe "when it has netmask, gateway, and device" do
before do
- @resource.target("charmander")
- @resource.netmask("lemask")
- @resource.gateway("111.111.111")
- @resource.device("forcefield")
+ resource.target("charmander")
+ resource.netmask("lemask")
+ resource.gateway("111.111.111")
+ resource.device("forcefield")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:netmask]).to eq("lemask")
expect(state[:gateway]).to eq("111.111.111")
end
it "returns the target as its identity" do
- expect(@resource.identity).to eq("charmander")
+ expect(resource.identity).to eq("charmander")
end
end
end
diff --git a/spec/unit/resource/rpm_package_spec.rb b/spec/unit/resource/rpm_package_spec.rb
index e1488f1dd1..eeeddd9bee 100644
--- a/spec/unit/resource/rpm_package_spec.rb
+++ b/spec/unit/resource/rpm_package_spec.rb
@@ -34,13 +34,29 @@ describe Chef::Resource::RpmPackage, "initialize" do
end
describe Chef::Resource::RpmPackage, "allow_downgrade" do
- before(:each) do
- @resource = Chef::Resource::RpmPackage.new("foo")
+ let(:resource) { Chef::Resource::RpmPackage.new("foo") }
+
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
- it "should allow you to specify whether allow_downgrade is true or false" do
- expect { @resource.allow_downgrade true }.not_to raise_error
- expect { @resource.allow_downgrade false }.not_to raise_error
- expect { @resource.allow_downgrade "monkey" }.to raise_error(ArgumentError)
+ it "allows you to specify whether allow_downgrade is true or false" do
+ expect { resource.allow_downgrade true }.not_to raise_error
+ expect { resource.allow_downgrade false }.not_to raise_error
+ expect { resource.allow_downgrade "monkey" }.to raise_error(ArgumentError)
end
end
diff --git a/spec/unit/resource/ruby_block_spec.rb b/spec/unit/resource/ruby_block_spec.rb
index f393fbea46..fb5a8815c7 100644
--- a/spec/unit/resource/ruby_block_spec.rb
+++ b/spec/unit/resource/ruby_block_spec.rb
@@ -21,41 +21,38 @@ require "spec_helper"
describe Chef::Resource::RubyBlock do
- before(:each) do
- @resource = Chef::Resource::RubyBlock.new("fakey_fakerton")
+ let(:resource) { Chef::Resource::RubyBlock.new("fakey_fakerton") }
+
+ it "has a resource name of :ruby_block" do
+ expect(resource.resource_name).to eql(:ruby_block)
end
- it "should create a new Chef::Resource::RubyBlock" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::RubyBlock)
+ it "the block_name property is the name_property" do
+ expect(resource.block_name).to eql("fakey_fakerton")
end
- it "should have a default action of 'run'" do
- expect(@resource.action).to eql([:run])
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
- it "should have a resource name of :ruby_block" do
- expect(@resource.resource_name).to eql(:ruby_block)
+ it "supports :create, :run actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :run }.not_to raise_error
end
- it "should accept a ruby block/proc/.. for the 'block' parameter" do
- expect(@resource.block do
+ it "accepts a ruby block/proc/.. for the 'block' parameter" do
+ expect(resource.block do
"foo"
end.call).to eql("foo")
end
- it "allows the action to be 'create'" do
- @resource.action :create
- expect(@resource.action).to eq([:create])
- end
-
describe "when it has been initialized with block code" do
before do
- @resource.block_name("puts 'harrrr'")
+ resource.block_name("puts 'harrrr'")
end
it "returns the block as its identity" do
- expect(@resource.identity).to eq("puts 'harrrr'")
+ expect(resource.identity).to eq("puts 'harrrr'")
end
end
end
diff --git a/spec/unit/resource/ruby_spec.rb b/spec/unit/resource/ruby_spec.rb
index d7b6759462..88ebc3404e 100644
--- a/spec/unit/resource/ruby_spec.rb
+++ b/spec/unit/resource/ruby_spec.rb
@@ -19,22 +19,21 @@
require "spec_helper"
describe Chef::Resource::Ruby do
+ let(:resource) { Chef::Resource::Ruby.new("fakey_fakerton") }
- before(:each) do
- @resource = Chef::Resource::Ruby.new("fakey_fakerton")
+ it "has a resource name of :ruby" do
+ expect(resource.resource_name).to eql(:ruby)
end
- it "should create a new Chef::Resource::Ruby" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Ruby)
+ it "sets the default action as :run" do
+ expect(resource.action).to eql([:run])
end
- it "should have a resource name of :ruby" do
- expect(@resource.resource_name).to eql(:ruby)
+ it "supports :run action" do
+ expect { resource.action :run }.not_to raise_error
end
- it "should have an interpreter of ruby" do
- expect(@resource.interpreter).to eql("ruby")
+ it "has 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 679b3bc1fc..be529a3832 100644
--- a/spec/unit/resource/scm_spec.rb
+++ b/spec/unit/resource/scm_spec.rb
@@ -20,174 +20,164 @@
require "spec_helper"
describe Chef::Resource::Scm do
+ let(:resource) { Chef::Resource::Scm.new("fakey_fakerton") }
- before(:each) do
- @resource = Chef::Resource::Scm.new("my awesome app")
+ it "the destination property is the name_property" do
+ expect(resource.destination).to eql("fakey_fakerton")
end
- it "should be a SCM resource" do
- expect(@resource).to be_a_kind_of(Chef::Resource::Scm)
+ it "sets the default action as :sync" do
+ expect(resource.action).to eql([:sync])
end
- it "supports :checkout, :export, :sync, :diff, and :log actions" do
- expect(@resource.allowed_actions).to include(:checkout)
- expect(@resource.allowed_actions).to include(:export)
- expect(@resource.allowed_actions).to include(:sync)
- expect(@resource.allowed_actions).to include(:diff)
- expect(@resource.allowed_actions).to include(:log)
+ it "supports :checkout, :diff, :export, :log, :sync actions" do
+ expect { resource.action :checkout }.not_to raise_error
+ expect { resource.action :diff }.not_to raise_error
+ expect { resource.action :export }.not_to raise_error
+ expect { resource.action :log }.not_to raise_error
+ expect { resource.action :sync }.not_to raise_error
end
it "takes the destination path as a string" do
- @resource.destination "/path/to/deploy/dir"
- expect(@resource.destination).to eql("/path/to/deploy/dir")
+ resource.destination "/path/to/deploy/dir"
+ expect(resource.destination).to eql("/path/to/deploy/dir")
end
it "takes a string for the repository URL" do
- @resource.repository "git://github.com/opscode/chef.git"
- expect(@resource.repository).to eql("git://github.com/opscode/chef.git")
+ resource.repository "git://github.com/opscode/chef.git"
+ expect(resource.repository).to eql("git://github.com/opscode/chef.git")
end
it "takes a string for the revision" do
- @resource.revision "abcdef"
- expect(@resource.revision).to eql("abcdef")
+ resource.revision "abcdef"
+ expect(resource.revision).to eql("abcdef")
end
it "defaults to the ``HEAD'' revision" do
- expect(@resource.revision).to eql("HEAD")
+ expect(resource.revision).to eql("HEAD")
end
it "takes a string for the user to run as" do
- @resource.user "dr_deploy"
- expect(@resource.user).to eql("dr_deploy")
+ resource.user "dr_deploy"
+ expect(resource.user).to eql("dr_deploy")
end
it "also takes an integer for the user to run as" do
- @resource.user 0
- expect(@resource.user).to eql(0)
+ resource.user 0
+ expect(resource.user).to eql(0)
end
it "takes a string for the group to run as, defaulting to nil" do
- expect(@resource.group).to be_nil
- @resource.group "opsdevs"
- expect(@resource.group).to eq("opsdevs")
+ expect(resource.group).to be_nil
+ resource.group "opsdevs"
+ expect(resource.group).to eq("opsdevs")
end
it "also takes an integer for the group to run as" do
- @resource.group 23
- expect(@resource.group).to eq(23)
+ resource.group 23
+ expect(resource.group).to eq(23)
end
it "has a svn_username String attribute" do
- @resource.svn_username "moartestsplz"
- expect(@resource.svn_username).to eql("moartestsplz")
+ resource.svn_username "moartestsplz"
+ expect(resource.svn_username).to eql("moartestsplz")
end
it "has a svn_password String attribute" do
- @resource.svn_password "taftplz"
- expect(@resource.svn_password).to eql("taftplz")
- end
-
- it "has a svn_arguments String attribute" do
- @resource.svn_arguments "--more-taft plz"
- expect(@resource.svn_arguments).to eql("--more-taft plz")
- end
-
- it "has a svn_info_args String attribute" do
- expect(@resource.svn_info_args).to be_nil
- @resource.svn_info_args("--no-moar-plaintext-creds yep")
- expect(@resource.svn_info_args).to eq("--no-moar-plaintext-creds yep")
+ resource.svn_password "taftplz"
+ expect(resource.svn_password).to eql("taftplz")
end
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)
+ resource.depth 5
+ expect(resource.depth).to eq(5)
+ expect { resource.depth "five" }.to raise_error(ArgumentError)
end
it "defaults to nil depth for a full clone" do
- expect(@resource.depth).to be_nil
+ expect(resource.depth).to be_nil
end
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)
+ resource.enable_submodules true
+ expect(resource.enable_submodules).to be_truthy
+ expect { resource.enable_submodules "lolz" }.to raise_error(ArgumentError)
end
it "defaults to not enabling submodules" do
- expect(@resource.enable_submodules).to be_falsey
+ expect(resource.enable_submodules).to be_falsey
end
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)
+ resource.enable_checkout true
+ expect(resource.enable_checkout).to be_truthy
+ expect { resource.enable_checkout "lolz" }.to raise_error(ArgumentError)
end
it "defaults to enabling checkout" do
- expect(@resource.enable_checkout).to be_truthy
+ expect(resource.enable_checkout).to be_truthy
end
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)
+ resource.remote "opscode"
+ expect(resource.remote).to eql("opscode")
+ expect { resource.remote 1337 }.to raise_error(ArgumentError)
end
it "defaults to ``origin'' for the remote" do
- expect(@resource.remote).to eq("origin")
+ expect(resource.remote).to eq("origin")
end
it "takes a string for the ssh wrapper" do
- @resource.ssh_wrapper "with_ssh_fu"
- expect(@resource.ssh_wrapper).to eql("with_ssh_fu")
+ resource.ssh_wrapper "with_ssh_fu"
+ expect(resource.ssh_wrapper).to eql("with_ssh_fu")
end
it "defaults to nil for the ssh wrapper" do
- expect(@resource.ssh_wrapper).to be_nil
+ expect(resource.ssh_wrapper).to be_nil
end
it "defaults to nil for the environment" do
- expect(@resource.environment).to be_nil
+ expect(resource.environment).to be_nil
end
describe "when it has a timeout attribute" do
let(:ten_seconds) { 10 }
- before { @resource.timeout(ten_seconds) }
+ before { resource.timeout(ten_seconds) }
it "stores this timeout" do
- expect(@resource.timeout).to eq(ten_seconds)
+ expect(resource.timeout).to eq(ten_seconds)
end
end
describe "when it has no timeout attribute" do
- it "should have no default timeout" do
- expect(@resource.timeout).to be_nil
+ it "has no default timeout" do
+ expect(resource.timeout).to be_nil
end
end
describe "when it has repository, revision, user, and group" do
before do
- @resource.destination("hell")
- @resource.repository("apt")
- @resource.revision("1.2.3")
- @resource.user("root")
- @resource.group("super_adventure_club")
+ resource.destination("hell")
+ resource.repository("apt")
+ resource.revision("1.2.3")
+ resource.user("root")
+ resource.group("super_adventure_club")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:revision]).to eq("1.2.3")
end
it "returns the destination as its identity" do
- expect(@resource.identity).to eq("hell")
+ expect(resource.identity).to eq("hell")
end
end
describe "when it has a environment attribute" do
let(:test_environment) { { "CHEF_ENV" => "/tmp" } }
- before { @resource.environment(test_environment) }
+ before { resource.environment(test_environment) }
it "stores this environment" do
- expect(@resource.environment).to eq(test_environment)
+ expect(resource.environment).to eq(test_environment)
end
end
end
diff --git a/spec/unit/resource/script_spec.rb b/spec/unit/resource/script_spec.rb
index 16f7650712..3306ddb666 100644
--- a/spec/unit/resource/script_spec.rb
+++ b/spec/unit/resource/script_spec.rb
@@ -24,7 +24,15 @@ describe Chef::Resource::Script do
let(:script_resource) { Chef::Resource::Script.new(resource_instance_name) }
let(:resource_name) { :script }
- it "should accept a string for the interpreter" do
+ it "sets the default action as :run" do
+ expect(script_resource.action).to eql([:run])
+ end
+
+ it "supports :run action" do
+ expect { script_resource.action :run }.not_to raise_error
+ end
+
+ it "accepts a string for the interpreter" do
script_resource.interpreter "naaaaNaNaNaaNaaNaaNaa"
expect(script_resource.interpreter).to eql("naaaaNaNaNaaNaaNaaNaa")
end
diff --git a/spec/unit/resource/service_spec.rb b/spec/unit/resource/service_spec.rb
index 67a4635983..963c2b2d89 100644
--- a/spec/unit/resource/service_spec.rb
+++ b/spec/unit/resource/service_spec.rb
@@ -20,180 +20,187 @@
require "spec_helper"
describe Chef::Resource::Service do
+ let(:resource) { Chef::Resource::Service.new("chef") }
- before(:each) do
- @resource = Chef::Resource::Service.new("chef")
+ it "does not set a provider unless node[:init_package] is defined as systemd" do
+ expect(resource.provider).to eq(nil)
end
- it "should create a new Chef::Resource::Service" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::Service)
+ it "sets the service_name to the first argument to new" do
+ expect(resource.service_name).to eql("chef")
end
- it "should not set a provider unless node[:init_package] is defined as systemd" do
- expect(@resource.provider).to eq(nil)
+ it "sets the default action as :nothing" do
+ expect(resource.action).to eql([:nothing])
end
- it "should set the service_name to the first argument to new" do
- expect(@resource.service_name).to eql("chef")
+ it "supports :disable, :enable, :mask, :reload, :restart, :start, :stop, :unmask actions" do
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ expect { resource.action :mask }.not_to raise_error
+ expect { resource.action :reload }.not_to raise_error
+ expect { resource.action :restart }.not_to raise_error
+ expect { resource.action :start }.not_to raise_error
+ expect { resource.action :stop }.not_to raise_error
+ expect { resource.action :unmask }.not_to raise_error
end
- it "should set the pattern to be the service name by default" do
- expect(@resource.pattern).to eql("chef")
+ it "sets the pattern to be the service name by default" do
+ expect(resource.pattern).to eql("chef")
end
- it "should accept a string for the service name" do
- @resource.service_name "something"
- expect(@resource.service_name).to eql("something")
+ it "accepts a string for the service name" do
+ resource.service_name "something"
+ expect(resource.service_name).to eql("something")
end
- it "should accept a string for the service pattern" do
- @resource.pattern ".*"
- expect(@resource.pattern).to eql(".*")
+ it "accepts a string for the service pattern" do
+ resource.pattern ".*"
+ expect(resource.pattern).to eql(".*")
end
- it "should not accept a regexp for the service pattern" do
+ it "does not accept a regexp for the service pattern" do
expect do
- @resource.pattern /.*/
+ resource.pattern /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service start command" do
- @resource.start_command "/etc/init.d/chef start"
- expect(@resource.start_command).to eql("/etc/init.d/chef start")
+ it "accepts a string for the service start command" do
+ resource.start_command "/etc/init.d/chef start"
+ expect(resource.start_command).to eql("/etc/init.d/chef start")
end
- it "should not accept a regexp for the service start command" do
+ it "does not accept a regexp for the service start command" do
expect do
- @resource.start_command /.*/
+ resource.start_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service stop command" do
- @resource.stop_command "/etc/init.d/chef stop"
- expect(@resource.stop_command).to eql("/etc/init.d/chef stop")
+ it "accepts a string for the service stop command" do
+ resource.stop_command "/etc/init.d/chef stop"
+ expect(resource.stop_command).to eql("/etc/init.d/chef stop")
end
- it "should not accept a regexp for the service stop command" do
+ it "does not accept a regexp for the service stop command" do
expect do
- @resource.stop_command /.*/
+ resource.stop_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service status command" do
- @resource.status_command "/etc/init.d/chef status"
- expect(@resource.status_command).to eql("/etc/init.d/chef status")
+ it "accepts a string for the service status command" do
+ resource.status_command "/etc/init.d/chef status"
+ expect(resource.status_command).to eql("/etc/init.d/chef status")
end
- it "should not accept a regexp for the service status command" do
+ it "does not accept a regexp for the service status command" do
expect do
- @resource.status_command /.*/
+ resource.status_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service restart command" do
- @resource.restart_command "/etc/init.d/chef restart"
- expect(@resource.restart_command).to eql("/etc/init.d/chef restart")
+ it "accepts a string for the service restart command" do
+ resource.restart_command "/etc/init.d/chef restart"
+ expect(resource.restart_command).to eql("/etc/init.d/chef restart")
end
- it "should not accept a regexp for the service restart command" do
+ it "does not accept a regexp for the service restart command" do
expect do
- @resource.restart_command /.*/
+ resource.restart_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service reload command" do
- @resource.reload_command "/etc/init.d/chef reload"
- expect(@resource.reload_command).to eql("/etc/init.d/chef reload")
+ it "accepts a string for the service reload command" do
+ resource.reload_command "/etc/init.d/chef reload"
+ expect(resource.reload_command).to eql("/etc/init.d/chef reload")
end
- it "should not accept a regexp for the service reload command" do
+ it "does not accept a regexp for the service reload command" do
expect do
- @resource.reload_command /.*/
+ resource.reload_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept a string for the service init command" do
- @resource.init_command "/etc/init.d/chef"
- expect(@resource.init_command).to eql("/etc/init.d/chef")
+ it "accepts a string for the service init command" do
+ resource.init_command "/etc/init.d/chef"
+ expect(resource.init_command).to eql("/etc/init.d/chef")
end
- it "should not accept a regexp for the service init command" do
+ it "does not accept a regexp for the service init command" do
expect do
- @resource.init_command /.*/
+ resource.init_command /.*/
end.to raise_error(ArgumentError)
end
- it "should accept an array for options" do
- @resource.options ["-r", "-s"]
- expect(@resource.options).to eql(["-r", "-s"])
+ it "accepts an array for options" do
+ resource.options ["-r", "-s"]
+ expect(resource.options).to eql(["-r", "-s"])
end
- it "should accept a string for options" do
- @resource.options "-r"
- expect(@resource.options).to eql(["-r"])
+ it "accepts a string for options" do
+ resource.options "-r"
+ expect(resource.options).to eql(["-r"])
end
- it "should accept a string with multiple flags for options" do
- @resource.options "-r -s"
- expect(@resource.options).to eql(["-r", "-s"])
+ it "accepts a string with multiple flags for options" do
+ resource.options "-r -s"
+ expect(resource.options).to eql(["-r", "-s"])
end
- it "should not accept a boolean for options" do
+ it "does not accept a boolean for options" do
expect do
- @resource.options true
+ resource.options true
end.to raise_error(ArgumentError)
end
%w{enabled running}.each do |attrib|
- it "should accept true for #{attrib}" do
- @resource.send(attrib, true)
- expect(@resource.send(attrib)).to eql(true)
+ it "accepts true for #{attrib}" do
+ resource.send(attrib, true)
+ expect(resource.send(attrib)).to eql(true)
end
- it "should accept false for #{attrib}" do
- @resource.send(attrib, false)
- expect(@resource.send(attrib)).to eql(false)
+ it "accepts false for #{attrib}" do
+ resource.send(attrib, false)
+ expect(resource.send(attrib)).to eql(false)
end
- it "should not accept a string for #{attrib}" do
- expect { @resource.send(attrib, "poop") }.to raise_error(ArgumentError)
+ it "does not accept a string for #{attrib}" do
+ expect { resource.send(attrib, "poop") }.to raise_error(ArgumentError)
end
- it "should default all the feature support to nil" do
- support_hash = { :status => nil, :restart => nil, :reload => nil }
- expect(@resource.supports).to eq(support_hash)
+ it "defaults all the feature support to nil" do
+ support_hash = { status: nil, restart: nil, reload: nil }
+ expect(resource.supports).to eq(support_hash)
end
- it "should allow you to set what features this resource supports as a array" do
+ it "allows you to set what features this resource supports as a array" do
support_array = [ :status, :restart ]
- support_hash = { :status => true, :restart => true }
- @resource.supports(support_array)
- expect(@resource.supports).to eq(support_hash)
+ support_hash = { status: true, restart: true }
+ resource.supports(support_array)
+ expect(resource.supports).to eq(support_hash)
end
- it "should allow you to set what features this resource supports as a hash" do
- support_hash = { :status => true, :restart => true }
- @resource.supports(support_hash)
- expect(@resource.supports).to eq(support_hash)
+ it "allows you to set what features this resource supports as a hash" do
+ support_hash = { status: true, restart: true }
+ resource.supports(support_hash)
+ expect(resource.supports).to eq(support_hash)
end
end
describe "when it has pattern and supports" do
before do
- @resource.service_name("superfriend")
- @resource.enabled(true)
- @resource.running(false)
+ resource.service_name("superfriend")
+ resource.enabled(true)
+ resource.running(false)
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:enabled]).to eql(true)
expect(state[:running]).to eql(false)
end
it "returns the service name as its identity" do
- expect(@resource.identity).to eq("superfriend")
+ 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 56c0fbdb8b..d64b8c0170 100644
--- a/spec/unit/resource/smartos_package_spec.rb
+++ b/spec/unit/resource/smartos_package_spec.rb
@@ -1,6 +1,7 @@
#
# Author:: Thomas Bishop (<bishop.thomas@gmail.com>)
# Copyright:: Copyright 2010-2016, Thomas Bishop
+# Copyright:: Copyright 2018, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,9 +18,8 @@
#
require "spec_helper"
-require "support/shared/unit/resource/static_provider_resolution"
-describe Chef::Resource::SmartosPackage, "initialize" do
+describe Chef::Resource::SmartosPackage do
static_provider_resolution(
resource: Chef::Resource::SmartosPackage,
@@ -30,4 +30,23 @@ describe Chef::Resource::SmartosPackage, "initialize" do
platform_family: "smartos"
)
+ let(:resource) { Chef::Resource::SmartosPackage.new("fakey_fakerton") }
+
+ it "sets the package_name to the name provided" do
+ expect(resource.package_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
end
diff --git a/spec/unit/resource/solaris_package_spec.rb b/spec/unit/resource/solaris_package_spec.rb
index 1f1ef4da30..3502b6b6b8 100644
--- a/spec/unit/resource/solaris_package_spec.rb
+++ b/spec/unit/resource/solaris_package_spec.rb
@@ -32,11 +32,23 @@ describe Chef::Resource::SolarisPackage, "initialize" do
)
end
- before(:each) do
- @resource = Chef::Resource::SolarisPackage.new("foo")
+ let(:resource) { Chef::Resource::SolarisPackage.new("foo") }
+
+ it "sets the package_name to the name provided" do
+ expect(resource.package_name).to eql("foo")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
end
- it "should set the package_name to the name provided" do
- expect(@resource.package_name).to eql("foo")
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
end
diff --git a/spec/unit/resource/ssh_known_hosts_entry_spec.rb b/spec/unit/resource/ssh_known_hosts_entry_spec.rb
new file mode 100644
index 0000000000..3bae37dfe7
--- /dev/null
+++ b/spec/unit/resource/ssh_known_hosts_entry_spec.rb
@@ -0,0 +1,55 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::SshKnownHostsEntry do
+ let(:node) { Chef::Node.new }
+ let(:run_context) do
+ node.automatic[:root_group] = "superduper"
+ empty_events = Chef::EventDispatch::Dispatcher.new
+ Chef::RunContext.new(node, {}, empty_events)
+ end
+ let(:resource) { Chef::Resource::SshKnownHostsEntry.new("example.com", run_context) }
+
+ it "is not a preview resource in Chef 15" do
+ pending("Chef 15") unless Chef::VERSION.start_with?("15")
+ expect(resource.class.preview_resource).to be_falsey
+ end
+
+ it "sets resource name as :ssh_known_hosts_entry" do
+ expect(resource.resource_name).to eql(:ssh_known_hosts_entry)
+ end
+
+ it "sets group property to node['root_group'] by default" do
+ expect(resource.group).to eql("superduper")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "sets the host property as its name property" do
+ expect(resource.host).to eql("example.com")
+ end
+
+ it "supports :create and :flush actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :flush }.not_to raise_error
+ expect { resource.action :delete }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/subversion_spec.rb b/spec/unit/resource/subversion_spec.rb
index a2901bf53b..b29c880b91 100644
--- a/spec/unit/resource/subversion_spec.rb
+++ b/spec/unit/resource/subversion_spec.rb
@@ -17,10 +17,8 @@
#
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,
@@ -28,44 +26,66 @@ describe Chef::Resource::Subversion do
action: :install
)
- before do
- @svn = Chef::Resource::Subversion.new("ohai, svn project!")
- end
+ let(:resource) { Chef::Resource::Subversion.new("fakey_fakerton") }
it "is a subclass of Resource::Scm" do
- expect(@svn).to be_an_instance_of(Chef::Resource::Subversion)
- expect(@svn).to be_a_kind_of(Chef::Resource::Scm)
+ expect(resource).to be_a_kind_of(Chef::Resource::Scm)
+ end
+
+ it "the destination property is the name_property" do
+ expect(resource.destination).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :sync" do
+ expect(resource.action).to eql([:sync])
end
- it "allows the force_export action" do
- expect(@svn.allowed_actions).to include(:force_export)
+ it "supports :checkout, :diff, :export, :force_export, :log, :sync actions" do
+ expect { resource.action :checkout }.not_to raise_error
+ expect { resource.action :diff }.not_to raise_error
+ expect { resource.action :export }.not_to raise_error
+ expect { resource.action :force_export }.not_to raise_error
+ expect { resource.action :log }.not_to raise_error
+ expect { resource.action :sync }.not_to raise_error
end
it "sets svn info arguments to --no-auth-cache by default" do
- expect(@svn.svn_info_args).to eq("--no-auth-cache")
+ expect(resource.svn_info_args).to eq("--no-auth-cache")
end
it "resets svn info arguments to nil when given false in the setter" do
- @svn.svn_info_args(false)
- expect(@svn.svn_info_args).to be_nil
+ resource.svn_info_args(false)
+ expect(resource.svn_info_args).to be_nil
end
it "sets svn arguments to --no-auth-cache by default" do
- expect(@svn.svn_arguments).to eq("--no-auth-cache")
+ expect(resource.svn_arguments).to eq("--no-auth-cache")
end
it "sets svn binary to nil by default" do
- expect(@svn.svn_binary).to be_nil
+ expect(resource.svn_binary).to be_nil
end
it "resets svn arguments to nil when given false in the setter" do
- @svn.svn_arguments(false)
- expect(@svn.svn_arguments).to be_nil
+ resource.svn_arguments(false)
+ expect(resource.svn_arguments).to be_nil
+ end
+
+ it "has a svn_arguments String attribute" do
+ expect(resource.svn_arguments).to eq("--no-auth-cache") # the default
+ resource.svn_arguments "--more-taft plz"
+ expect(resource.svn_arguments).to eql("--more-taft plz")
+ end
+
+ it "has a svn_info_args String attribute" do
+ expect(resource.svn_info_args).to eq("--no-auth-cache") # the default
+ resource.svn_info_args("--no-moar-plaintext-creds yep")
+ expect(resource.svn_info_args).to eq("--no-moar-plaintext-creds yep")
end
it "hides password from custom exception message" do
- @svn.svn_password "l33th4x0rpa$$w0rd"
- e = @svn.customize_exception(Chef::Exceptions::Exec.new "Exception with password #{@svn.svn_password}")
- expect(e.message.include?(@svn.svn_password)).to be_falsey
+ resource.svn_password "l33th4x0rpa$$w0rd"
+ e = resource.customize_exception(Chef::Exceptions::Exec.new "Exception with password #{resource.svn_password}")
+ expect(e.message.include?(resource.svn_password)).to be_falsey
end
end
diff --git a/spec/unit/resource/sudo_spec.rb b/spec/unit/resource/sudo_spec.rb
new file mode 100644
index 0000000000..adad4a30f8
--- /dev/null
+++ b/spec/unit/resource/sudo_spec.rb
@@ -0,0 +1,99 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::Sudo do
+
+ let(:node) { Chef::Node.new }
+ let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:run_context) { Chef::RunContext.new(node, {}, events) }
+ let(:resource) { Chef::Resource::Sudo.new("fakey_fakerton", run_context) }
+
+ it "has a resource name of :sudo" do
+ expect(resource.resource_name).to eql(:sudo)
+ end
+
+ it "the filename property is the name_property" do
+ expect(resource.filename).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :delete, :install, :remove actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "coerces filename property values . & ~ to __" do
+ resource.filename "something.something~"
+ expect(resource.filename).to eql("something__something__")
+ end
+
+ it "supports the legacy 'user' property" do
+ resource.user ["foo"]
+ expect(resource.users).to eql(["foo"])
+ end
+
+ it "supports the legacy 'groups' property" do
+ resource.group ["%foo"]
+ expect(resource.groups).to eql(["%foo"])
+ end
+
+ it "coerces users & groups String vals to Arrays" do
+ resource.users "something"
+ resource.groups "%something"
+ expect(resource.users).to eql(["something"])
+ expect(resource.groups).to eql(["%something"])
+ end
+
+ it "coerces users & group String vals no matter the spacing" do
+ resource.users "user1, user2 , user3 ,user4"
+ resource.groups "group1, group2 , group3 ,group4"
+ expect(resource.users).to eql(%w{user1 user2 user3 user4})
+ expect(resource.groups).to eql(["%group1", "%group2", "%group3", "%group4"])
+ end
+
+ it "coerces groups values to properly start with %" do
+ resource.groups ["foo", "%bar"]
+ expect(resource.groups).to eql(["%foo", "%bar"])
+ end
+
+ it "it sets the config prefix to /etc on linux" do
+ node.automatic[:platform_family] = "debian"
+ expect(resource.config_prefix).to eql("/etc")
+ end
+
+ it "it sets the config prefix to /private/etc on macOS" do
+ node.automatic[:platform_family] = "mac_os_x"
+ expect(resource.config_prefix).to eql("/private/etc")
+ end
+
+ it "it sets the config prefix to /usr/local/etc on FreeBSD" do
+ node.automatic[:platform_family] = "freebsd"
+ expect(resource.config_prefix).to eql("/usr/local/etc")
+ end
+
+ it "it sets the config prefix to /opt/local/etc on smartos" do
+ node.automatic[:platform_family] = "smartos"
+ expect(resource.config_prefix).to eql("/opt/local/etc")
+ end
+end
diff --git a/spec/unit/resource/swap_file_spec.rb b/spec/unit/resource/swap_file_spec.rb
new file mode 100644
index 0000000000..9ebd50fa9a
--- /dev/null
+++ b/spec/unit/resource/swap_file_spec.rb
@@ -0,0 +1,39 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::SwapFile do
+ let(:resource) { Chef::Resource::SwapFile.new("fakey_fakerton") }
+
+ it "sets resource name as :swap_file" do
+ expect(resource.resource_name).to eql(:swap_file)
+ end
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :remove actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/sysctl_spec.rb b/spec/unit/resource/sysctl_spec.rb
new file mode 100644
index 0000000000..ba4b23f098
--- /dev/null
+++ b/spec/unit/resource/sysctl_spec.rb
@@ -0,0 +1,54 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::Sysctl do
+ let(:resource) { Chef::Resource::Sysctl.new("fakey_fakerton") }
+
+ it "sets resource name as :sysctl" do
+ expect(resource.resource_name).to eql(:sysctl)
+ end
+
+ it "the key property is the name_property" do
+ expect(resource.key).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :apply" do
+ expect(resource.action).to eql([:apply])
+ end
+
+ it "supports :apply, :remove actions" do
+ expect { resource.action :apply }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "coerces Arrays in the value property to space delimited Strings" do
+ resource.value [1, 2, 3]
+ expect(resource.value).to eql("1 2 3")
+ end
+
+ it "coerces Integers in the value property to Strings" do
+ resource.value 1
+ expect(resource.value).to eql("1")
+ end
+
+ it "coerces Floats in the value property to Strings" do
+ resource.value 1.1
+ expect(resource.value).to eql("1.1")
+ end
+end
diff --git a/spec/unit/resource/systemd_unit_spec.rb b/spec/unit/resource/systemd_unit_spec.rb
index ab1004fab0..fa30255885 100644
--- a/spec/unit/resource/systemd_unit_spec.rb
+++ b/spec/unit/resource/systemd_unit_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Nathan Williams (<nath.e.will@gmail.com>)
-# Copyright:: Copyright 2016, Nathan Williams
+# Copyright:: Copyright 2016-2018, Nathan Williams
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,12 +19,8 @@
require "spec_helper"
describe Chef::Resource::SystemdUnit do
- before(:each) do
- @resource = Chef::Resource::SystemdUnit.new("sysstat-collect.timer")
- end
-
+ let(:resource) { Chef::Resource::SystemdUnit.new("sysstat-collect.timer") }
let(:unit_content_string) { "[Unit]\nDescription = Run system activity accounting tool every 10 minutes\n\n[Timer]\nOnCalendar = *:00/10\n\n[Install]\nWantedBy = sysstat.service\n" }
-
let(:unit_content_hash) do
{
"Unit" => {
@@ -39,77 +35,77 @@ describe Chef::Resource::SystemdUnit do
}
end
- it "creates a new Chef::Resource::SystemdUnit" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::SystemdUnit)
- end
-
- it "should have a name" do
- expect(@resource.name).to eql("sysstat-collect.timer")
+ it "the unit_name property is the name_property" do
+ expect(resource.unit_name).to eql("sysstat-collect.timer")
end
- it "has a default action of nothing" do
- expect(@resource.action).to eql([:nothing])
+ it "sets the default action as :nothing" do
+ expect(resource.action).to eql([:nothing])
end
- it "supports appropriate unit actions" do
- expect { @resource.action :create }.not_to raise_error
- expect { @resource.action :delete }.not_to raise_error
- expect { @resource.action :enable }.not_to raise_error
- expect { @resource.action :disable }.not_to raise_error
- expect { @resource.action :mask }.not_to raise_error
- expect { @resource.action :unmask }.not_to raise_error
- expect { @resource.action :start }.not_to raise_error
- expect { @resource.action :stop }.not_to raise_error
- expect { @resource.action :restart }.not_to raise_error
- expect { @resource.action :reload }.not_to raise_error
- expect { @resource.action :wrong }.to raise_error(ArgumentError)
+ it "supports :create, :delete, :disable, :enable, :mask, :preset, :reenable, :reload, :reload_or_restart, :reload_or_try_restart, :restart, :revert, :start, :stop, :try_restart, :unmask actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ expect { resource.action :mask }.not_to raise_error
+ expect { resource.action :preset }.not_to raise_error
+ expect { resource.action :reenable }.not_to raise_error
+ expect { resource.action :reload }.not_to raise_error
+ expect { resource.action :reload_or_restart }.not_to raise_error
+ expect { resource.action :reload_or_try_restart }.not_to raise_error
+ expect { resource.action :restart }.not_to raise_error
+ expect { resource.action :revert }.not_to raise_error
+ expect { resource.action :start }.not_to raise_error
+ expect { resource.action :stop }.not_to raise_error
+ expect { resource.action :try_restart }.not_to raise_error
+ expect { resource.action :unmask }.not_to raise_error
end
it "accepts boolean state properties" do
- expect { @resource.active false }.not_to raise_error
- expect { @resource.active true }.not_to raise_error
- expect { @resource.active "yes" }.to raise_error(ArgumentError)
+ expect { resource.active false }.not_to raise_error
+ expect { resource.active true }.not_to raise_error
+ expect { resource.active "yes" }.to raise_error(ArgumentError)
- expect { @resource.enabled true }.not_to raise_error
- expect { @resource.enabled false }.not_to raise_error
- expect { @resource.enabled "no" }.to raise_error(ArgumentError)
+ expect { resource.enabled true }.not_to raise_error
+ expect { resource.enabled false }.not_to raise_error
+ expect { resource.enabled "no" }.to raise_error(ArgumentError)
- expect { @resource.masked true }.not_to raise_error
- expect { @resource.masked false }.not_to raise_error
- expect { @resource.masked :nope }.to raise_error(ArgumentError)
+ expect { resource.masked true }.not_to raise_error
+ expect { resource.masked false }.not_to raise_error
+ expect { resource.masked :nope }.to raise_error(ArgumentError)
- expect { @resource.static true }.not_to raise_error
- expect { @resource.static false }.not_to raise_error
- expect { @resource.static "yep" }.to raise_error(ArgumentError)
+ expect { resource.static true }.not_to raise_error
+ expect { resource.static false }.not_to raise_error
+ expect { resource.static "yep" }.to raise_error(ArgumentError)
end
it "accepts the content property" do
- expect { @resource.content nil }.not_to raise_error
- expect { @resource.content "test" }.not_to raise_error
- expect { @resource.content({}) }.not_to raise_error
- expect { @resource.content 5 }.to raise_error(ArgumentError)
+ expect { resource.content nil }.not_to raise_error
+ expect { resource.content "test" }.not_to raise_error
+ expect { resource.content({}) }.not_to raise_error
+ expect { resource.content 5 }.to raise_error(ArgumentError)
end
it "accepts the user property" do
- expect { @resource.user nil }.not_to raise_error
- expect { @resource.user "deploy" }.not_to raise_error
- expect { @resource.user 5 }.to raise_error(ArgumentError)
+ expect { resource.user nil }.not_to raise_error
+ expect { resource.user "deploy" }.not_to raise_error
+ expect { resource.user 5 }.to raise_error(ArgumentError)
end
it "accepts the triggers_reload property" do
- expect { @resource.triggers_reload true }.not_to raise_error
- expect { @resource.triggers_reload false }.not_to raise_error
- expect { @resource.triggers_reload "no" }.to raise_error(ArgumentError)
+ expect { resource.triggers_reload true }.not_to raise_error
+ expect { resource.triggers_reload false }.not_to raise_error
+ expect { resource.triggers_reload "no" }.to raise_error(ArgumentError)
end
it "reports its state" do
- @resource.active true
- @resource.enabled true
- @resource.masked false
- @resource.static false
- @resource.content "test"
- state = @resource.state_for_resource_reporter
+ resource.active true
+ resource.enabled true
+ resource.masked false
+ resource.static false
+ resource.content "test"
+ state = resource.state_for_resource_reporter
expect(state[:active]).to eq(true)
expect(state[:enabled]).to eq(true)
expect(state[:masked]).to eq(false)
@@ -118,16 +114,16 @@ describe Chef::Resource::SystemdUnit do
end
it "returns the unit name as its identity" do
- expect(@resource.identity).to eq("sysstat-collect.timer")
+ expect(resource.identity).to eq("sysstat-collect.timer")
end
it "serializes to ini with a string-formatted content property" do
- @resource.content(unit_content_string)
- expect(@resource.to_ini).to eq unit_content_string
+ resource.content(unit_content_string)
+ expect(resource.to_ini).to eq unit_content_string
end
it "serializes to ini with a hash-formatted content property" do
- @resource.content(unit_content_hash)
- expect(@resource.to_ini).to eq unit_content_string
+ resource.content(unit_content_hash)
+ expect(resource.to_ini).to eq unit_content_string
end
end
diff --git a/spec/unit/resource/template_spec.rb b/spec/unit/resource/template_spec.rb
index 966a86ba6b..56af50517c 100644
--- a/spec/unit/resource/template_spec.rb
+++ b/spec/unit/resource/template_spec.rb
@@ -19,76 +19,90 @@
require "spec_helper"
describe Chef::Resource::Template do
+ let(:resource) { Chef::Resource::Template.new("fakey_fakerton") }
- before(:each) do
- @resource = Chef::Resource::Template.new("fakey_fakerton")
+ describe "initialize" do
+ it "is a subclass of Chef::Resource::File" do
+ expect(resource).to be_a_kind_of(Chef::Resource::File)
+ end
end
- describe "initialize" do
- it "should create a new Chef::Resource::Template" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::File)
- expect(@resource).to be_a_kind_of(Chef::Resource::Template)
+ describe "name" do
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
+ end
+ end
+
+ describe "Actions" do
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :create_if_missing, :delete, :touch actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :create_if_missing }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :touch }.not_to raise_error
end
end
describe "source" do
- it "should accept a string for the template source" do
- @resource.source "something"
- expect(@resource.source).to eql("something")
+ it "accepts a string for the template source" do
+ resource.source "something"
+ expect(resource.source).to eql("something")
end
- it "should have a default based on the param name with .erb appended" do
- expect(@resource.source).to eql("fakey_fakerton.erb")
+ it "has a default based on the param name with .erb appended" do
+ expect(resource.source).to eql("fakey_fakerton.erb")
end
- it "should use only the basename of the file as the default" do
+ it "uses only the basename of the file as the default" do
r = Chef::Resource::Template.new("/tmp/obit/fakey_fakerton")
expect(r.source).to eql("fakey_fakerton.erb")
end
end
describe "variables" do
- it "should accept a hash for the variable list" do
- @resource.variables({ :reluctance => :awkward })
- expect(@resource.variables).to eq({ :reluctance => :awkward })
+ it "accepts a hash for the variable list" do
+ resource.variables({ reluctance: :awkward })
+ expect(resource.variables).to eq({ reluctance: :awkward })
end
end
describe "cookbook" do
- it "should accept a string for the cookbook name" do
- @resource.cookbook("foo")
- expect(@resource.cookbook).to eq("foo")
+ it "accepts a string for the cookbook name" do
+ resource.cookbook("foo")
+ expect(resource.cookbook).to eq("foo")
end
- it "should default to nil" do
- expect(@resource.cookbook).to eq(nil)
+ it "defaults to nil" do
+ expect(resource.cookbook).to eq(nil)
end
end
describe "local" do
- it "should accept a boolean for whether a template is local or remote" do
- @resource.local(true)
- expect(@resource.local).to eq(true)
+ it "accepts a boolean for whether a template is local or remote" do
+ resource.local(true)
+ expect(resource.local).to eq(true)
end
- it "should default to false" do
- expect(@resource.local).to eq(false)
+ it "defaults to false" do
+ expect(resource.local).to eq(false)
end
end
describe "when it has a path, owner, group, mode, and checksum" do
before do
- @resource.path("/tmp/foo.txt")
- @resource.owner("root")
- @resource.group("wheel")
- @resource.mode("0644")
- @resource.checksum("1" * 64)
+ resource.path("/tmp/foo.txt")
+ resource.owner("root")
+ resource.group("wheel")
+ resource.mode("0644")
+ resource.checksum("1" * 64)
end
context "on unix", :unix_only do
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:owner]).to eq("root")
expect(state[:group]).to eq("wheel")
expect(state[:mode]).to eq("0644")
@@ -102,7 +116,7 @@ describe Chef::Resource::Template do
end
it "returns the file path as its identity" do
- expect(@resource.identity).to eq("/tmp/foo.txt")
+ expect(resource.identity).to eq("/tmp/foo.txt")
end
end
@@ -115,16 +129,16 @@ describe Chef::Resource::Template do
end
it "collects helper method bodies as blocks" do
- @resource.helper(:example_1) { "example_1" }
- @resource.helper(:example_2) { "example_2" }
- expect(@resource.inline_helper_blocks[:example_1].call).to eq("example_1")
- expect(@resource.inline_helper_blocks[:example_2].call).to eq("example_2")
+ resource.helper(:example_1) { "example_1" }
+ resource.helper(:example_2) { "example_2" }
+ expect(resource.inline_helper_blocks[:example_1].call).to eq("example_1")
+ expect(resource.inline_helper_blocks[:example_2].call).to eq("example_2")
end
it "compiles helper methods into a module" do
- @resource.helper(:example_1) { "example_1" }
- @resource.helper(:example_2) { "example_2" }
- modules = @resource.helper_modules
+ resource.helper(:example_1) { "example_1" }
+ resource.helper(:example_2) { "example_2" }
+ modules = resource.helper_modules
expect(modules.size).to eq(1)
o = Object.new
modules.each { |m| o.extend(m) }
@@ -133,38 +147,38 @@ describe Chef::Resource::Template do
end
it "compiles helper methods with arguments into a module" do
- @resource.helper(:shout) { |quiet| quiet.upcase }
- modules = @resource.helper_modules
+ resource.helper(:shout) { |quiet| quiet.upcase }
+ modules = resource.helper_modules
o = Object.new
modules.each { |m| o.extend(m) }
expect(o.shout("shout")).to eq("SHOUT")
end
it "raises an error when attempting to define a helper method without a method body" do
- expect { @resource.helper(:example) }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helper(:example) }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "raises an error when attempting to define a helper method with a non-Symbod method name" do
- expect { @resource.helper("example") { "fail" } }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helper("example") { "fail" } }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "collects helper module bodies as blocks" do
- @resource.helpers do
+ resource.helpers do
def example_1
"example_1"
end
end
- module_body = @resource.inline_helper_modules.first
+ module_body = resource.inline_helper_modules.first
expect(module_body).to be_a(Proc)
end
it "compiles helper module bodies into modules" do
- @resource.helpers do
+ resource.helpers do
def example_1
"example_1"
end
end
- modules = @resource.helper_modules
+ modules = resource.helper_modules
expect(modules.size).to eq(1)
o = Object.new
modules.each { |m| o.extend(m) }
@@ -172,39 +186,37 @@ describe Chef::Resource::Template do
end
it "raises an error when no block or module name is given for helpers definition" do
- expect { @resource.helpers() }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helpers() }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "raises an error when a non-module is given for helpers definition" do
- expect { @resource.helpers("NotAModule") }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helpers("NotAModule") }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "raises an error when a module name and block are both given for helpers definition" do
- expect { @resource.helpers(ExampleHelpers) { module_code } }.to raise_error(Chef::Exceptions::ValidationFailed)
+ expect { resource.helpers(ExampleHelpers) { module_code } }.to raise_error(Chef::Exceptions::ValidationFailed)
end
it "collects helper modules" do
- @resource.helpers(ExampleHelpers)
- expect(@resource.helper_modules).to include(ExampleHelpers)
+ resource.helpers(ExampleHelpers)
+ expect(resource.helper_modules).to include(ExampleHelpers)
end
it "combines all helpers into a set of compiled modules" do
- @resource.helpers(ExampleHelpers)
- @resource.helpers do
+ resource.helpers(ExampleHelpers)
+ resource.helpers do
def inline_module
"inline_module"
end
end
- @resource.helper(:inline_method) { "inline_method" }
- expect(@resource.helper_modules.size).to eq(3)
+ resource.helper(:inline_method) { "inline_method" }
+ 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/user_spec.rb b/spec/unit/resource/user_spec.rb
index 1a3f0284e3..2a96c5328d 100644
--- a/spec/unit/resource/user_spec.rb
+++ b/spec/unit/resource/user_spec.rb
@@ -19,115 +19,104 @@
require "spec_helper"
describe Chef::Resource::User, "initialize" do
- before(:each) do
- @resource = Chef::Resource::User.new("adam")
- end
-
- it "should create a new Chef::Resource::User" do
- expect(@resource).to be_a_kind_of(Chef::Resource)
- expect(@resource).to be_a_kind_of(Chef::Resource::User)
- end
+ let(:resource) { Chef::Resource::User.new("adam") }
- it "should set the resource_name to :user" do
- expect(@resource.resource_name).to eql(:user_resource_abstract_base_class)
+ it "sets the resource_name to :user" do
+ expect(resource.resource_name).to eql(:user_resource_abstract_base_class)
end
- it "should set the username equal to the argument to initialize" do
- expect(@resource.username).to eql("adam")
+ it "sets the username equal to the argument to initialize" do
+ expect(resource.username).to eql("adam")
end
%w{comment uid gid home shell password}.each do |attrib|
- it "should set #{attrib} to nil" do
- expect(@resource.send(attrib)).to eql(nil)
+ it "sets #{attrib} to nil" do
+ expect(resource.send(attrib)).to eql(nil)
end
end
- it "should set action to :create" do
- expect(@resource.action).to eql([:create])
+ it "sets action to :create" do
+ expect(resource.action).to eql([:create])
end
- it "should set manage_home to false" do
- expect(@resource.manage_home).to eql(false)
+ it "sets manage_home to false" do
+ expect(resource.manage_home).to eql(false)
end
- it "should set non_unique to false" do
- expect(@resource.non_unique).to eql(false)
+ it "sets non_unique to false" do
+ expect(resource.non_unique).to eql(false)
end
- it "should set force to false" do
- expect(@resource.force).to eql(false)
+ it "sets force to false" do
+ expect(resource.force).to eql(false)
end
%w{create remove modify manage lock unlock}.each do |action|
- it "should allow action #{action}" do
- expect(@resource.allowed_actions.detect { |a| a == action.to_sym }).to eql(action.to_sym)
+ it "allows action #{action}" do
+ expect(resource.allowed_actions.detect { |a| a == action.to_sym }).to eql(action.to_sym)
end
end
- it "should accept domain users (@ or \ separator) on non-windows" 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")
+ it "accepts domain users (@ or \ separator) on non-windows" 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")
end
end
%w{username comment home shell password}.each do |attrib|
describe Chef::Resource::User, attrib do
- before(:each) do
- @resource = Chef::Resource::User.new("adam")
- end
+ let(:resource) { Chef::Resource::User.new("adam") }
- it "should allow a string" do
- @resource.send(attrib, "adam")
- expect(@resource.send(attrib)).to eql("adam")
+ it "allows a string" do
+ resource.send(attrib, "adam")
+ expect(resource.send(attrib)).to eql("adam")
end
- it "should not allow a hash" do
- expect { @resource.send(attrib, { :woot => "i found it" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(attrib, { woot: "i found it" }) }.to raise_error(ArgumentError)
end
end
end
%w{uid gid}.each do |attrib|
describe Chef::Resource::User, attrib do
- before(:each) do
- @resource = Chef::Resource::User.new("adam")
- end
+ let(:resource) { Chef::Resource::User.new("adam") }
- it "should allow a string" do
- @resource.send(attrib, "100")
- expect(@resource.send(attrib)).to eql("100")
+ it "allows a string" do
+ resource.send(attrib, "100")
+ expect(resource.send(attrib)).to eql("100")
end
- it "should allow an integer" do
- @resource.send(attrib, 100)
- expect(@resource.send(attrib)).to eql(100)
+ it "allows an integer" do
+ resource.send(attrib, 100)
+ expect(resource.send(attrib)).to eql(100)
end
- it "should not allow a hash" do
- expect { @resource.send(attrib, { :woot => "i found it" }) }.to raise_error(ArgumentError)
+ it "does not allow a hash" do
+ expect { resource.send(attrib, { woot: "i found it" }) }.to raise_error(ArgumentError)
end
end
describe "when it has uid, gid, and home" do
+ let(:resource) { Chef::Resource::User.new("root") }
+
before do
- @resource = Chef::Resource::User.new("root")
- @resource.uid(123)
- @resource.gid(456)
- @resource.home("/usr/local/root/")
+ resource.uid(123)
+ resource.gid(456)
+ resource.home("/usr/local/root/")
end
it "describes its state" do
- state = @resource.state_for_resource_reporter
+ state = resource.state_for_resource_reporter
expect(state[:uid]).to eq(123)
expect(state[:gid]).to eq(456)
expect(state[:home]).to eq("/usr/local/root/")
end
it "returns the username as its identity" do
- expect(@resource.identity).to eq("root")
+ expect(resource.identity).to eq("root")
end
end
-
end
diff --git a/spec/unit/resource/windows_ad_join_spec.rb b/spec/unit/resource/windows_ad_join_spec.rb
new file mode 100644
index 0000000000..87dd83cd49
--- /dev/null
+++ b/spec/unit/resource/windows_ad_join_spec.rb
@@ -0,0 +1,51 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsAdJoin do
+ let(:resource) { Chef::Resource::WindowsAdJoin.new("example.com") }
+
+ it "sets resource name as :windows_ad_join" do
+ expect(resource.resource_name).to eql(:windows_ad_join)
+ end
+
+ it "the domain_name property is the name_property" do
+ expect(resource.domain_name).to eql("example.com")
+ end
+
+ it "sets the default action as :join" do
+ expect(resource.action).to eql([:join])
+ end
+
+ it "supports :join action" do
+ expect { resource.action :join }.not_to raise_error
+ end
+
+ it "only accepts FQDNs for the domain_name property" do
+ expect { resource.domain_name "example" }.to raise_error(ArgumentError)
+ end
+
+ it "accepts :immediate, :reboot_now, :request_reboot, :delayed, or :never values for 'reboot' property" do
+ expect { resource.reboot :immediate }.not_to raise_error
+ expect { resource.reboot :delayed }.not_to raise_error
+ expect { resource.reboot :reboot_now }.not_to raise_error
+ expect { resource.reboot :request_reboot }.not_to raise_error
+ expect { resource.reboot :never }.not_to raise_error
+ expect { resource.reboot :nopenope }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/windows_auto_run_spec.rb b/spec/unit/resource/windows_auto_run_spec.rb
new file mode 100644
index 0000000000..6cdf927831
--- /dev/null
+++ b/spec/unit/resource/windows_auto_run_spec.rb
@@ -0,0 +1,50 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsAutorun do
+ let(:resource) { Chef::Resource::WindowsAutorun.new("fakey_fakerton") }
+
+ it "sets resource name as :windows_auto_run" do
+ expect(resource.resource_name).to eql(:windows_auto_run)
+ end
+
+ it "the program_name property is the name_property" do
+ expect(resource.program_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :remove actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "supports :machine and :user in the root property" do
+ expect { resource.root :user }.not_to raise_error
+ expect { resource.root :machine }.not_to raise_error
+ expect { resource.root "user" }.to raise_error(ArgumentError)
+ end
+
+ it "coerces forward slashes to backslashes for the path" do
+ resource.path "C:/something.exe"
+ expect(resource.path).to eql('C:\\something.exe')
+ end
+end
diff --git a/spec/unit/resource/windows_env_spec.rb b/spec/unit/resource/windows_env_spec.rb
new file mode 100644
index 0000000000..06b5af630a
--- /dev/null
+++ b/spec/unit/resource/windows_env_spec.rb
@@ -0,0 +1,75 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Tyler Cloke (<tyler@chef.io>)
+# Copyright:: Copyright 2010-2016, VMware, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsEnv do
+
+ let(:resource) { Chef::Resource::WindowsEnv.new("fakey_fakerton") }
+
+ it "creates a new Chef::Resource::WindowsEnv" do
+ expect(resource).to be_a_kind_of(Chef::Resource)
+ expect(resource).to be_a_kind_of(Chef::Resource::WindowsEnv)
+ end
+
+ it "the key_name property is the name_property" do
+ expect(resource.key_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :delete, :modify actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :modify }.not_to raise_error
+ end
+
+ it "accepts a string as the env value via 'value'" do
+ expect { resource.value "bar" }.not_to raise_error
+ end
+
+ it "does not accept a Hash for the env value via 'to'" do
+ expect { resource.value Hash.new }.to raise_error(ArgumentError)
+ end
+
+ it "allows you to set an env value via 'to'" do
+ resource.value "bar"
+ expect(resource.value).to eql("bar")
+ end
+
+ describe "when it has key name and value" do
+ before do
+ resource.key_name("charmander")
+ resource.value("level7")
+ resource.delim("hi")
+ end
+
+ it "describes its state" do
+ state = resource.state_for_resource_reporter
+ expect(state[:value]).to eq("level7")
+ end
+
+ it "returns the key name as its identity" do
+ expect(resource.identity).to eq("charmander")
+ end
+ end
+
+end
diff --git a/spec/unit/resource/windows_feature.rb b/spec/unit/resource/windows_feature.rb
new file mode 100644
index 0000000000..f01bc3b864
--- /dev/null
+++ b/spec/unit/resource/windows_feature.rb
@@ -0,0 +1,60 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsFeature do
+ let(:resource) { Chef::Resource::WindowsFeature.new("fakey_fakerton") }
+
+ it "sets resource name as :windows_feature" do
+ expect(resource.resource_name).to eql(:windows_feature)
+ end
+
+ it "the feature_name property is the name_property" do
+ expect(resource.feature_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :delete, :install, :remove actions" do
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "all property defaults to false" do
+ expect(resource.all).to eql(false)
+ end
+
+ it "management_tools property defaults to false" do
+ expect(resource.management_tools).to eql(false)
+ end
+
+ it "timeout property defaults to 600" do
+ expect(resource.timeout).to eql(600)
+ end
+
+ it "install_method accepts :windows_feature_dism, :windows_feature_powershell, and :windows_feature_servermanagercmd" do
+ expect { resource.install_method :windows_feature_dism }.not_to raise_error
+ expect { resource.install_method :windows_feature_powershell }.not_to raise_error
+ expect { resource.install_method :windows_feature_servermanagercmd }.not_to raise_error
+ expect { resource.install_method "windows_feature_servermanagercmd" }.to raise_error(ArgumentError)
+ end
+
+end
diff --git a/spec/unit/resource/windows_feature_dism.rb b/spec/unit/resource/windows_feature_dism.rb
new file mode 100644
index 0000000000..87d99ecbaf
--- /dev/null
+++ b/spec/unit/resource/windows_feature_dism.rb
@@ -0,0 +1,72 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsFeatureDism do
+ let(:node) { Chef::Node.new }
+ let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:run_context) { Chef::RunContext.new(node, {}, events) }
+ let(:resource) { Chef::Resource::WindowsFeatureDism.new(%w{SNMP DHCP}, run_context) }
+
+ it "sets resource name as :windows_feature_dism" do
+ expect(resource.resource_name).to eql(:windows_feature_dism)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "the feature_name property is the name_property" do
+ node.automatic[:platform_version] = "6.2.9200"
+ expect(resource.feature_name).to eql(%w{snmp dhcp})
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :delete, :install, :remove actions" do
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "coerces comma separated lists of features to a lowercase array on 2012+" do
+ node.automatic[:platform_version] = "6.2.9200"
+ resource.feature_name "SNMP, DHCP"
+ expect(resource.feature_name).to eql(%w{snmp dhcp})
+ end
+
+ it "coerces a single feature as a String to a lowercase array on 2012+" do
+ node.automatic[:platform_version] = "6.2.9200"
+ resource.feature_name "SNMP"
+ expect(resource.feature_name).to eql(["snmp"])
+ end
+
+ it "coerces comma separated lists of features to an array, but preserves case on < 2012" do
+ node.automatic[:platform_version] = "6.1.7601"
+ resource.feature_name "SNMP, DHCP"
+ expect(resource.feature_name).to eql(%w{SNMP DHCP})
+ end
+
+ it "coerces a single feature as a String to an array, but preserves case on < 2012" do
+ node.automatic[:platform_version] = "6.1.7601"
+ resource.feature_name "SNMP"
+ expect(resource.feature_name).to eql(["SNMP"])
+ end
+end
diff --git a/spec/unit/resource/windows_feature_powershell.rb b/spec/unit/resource/windows_feature_powershell.rb
new file mode 100644
index 0000000000..3dc1604361
--- /dev/null
+++ b/spec/unit/resource/windows_feature_powershell.rb
@@ -0,0 +1,72 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsFeaturePowershell do
+ let(:node) { Chef::Node.new }
+ let(:events) { Chef::EventDispatch::Dispatcher.new }
+ let(:run_context) { Chef::RunContext.new(node, {}, events) }
+ let(:resource) { Chef::Resource::WindowsFeaturePowershell.new(%w{SNMP DHCP}, run_context) }
+
+ it "sets resource name as :windows_feature_powershell" do
+ expect(resource.resource_name).to eql(:windows_feature_powershell)
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "the feature_name property is the name_property" do
+ node.automatic[:platform_version] = "6.2.9200"
+ expect(resource.feature_name).to eql(%w{snmp dhcp})
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :delete, :install, :remove actions" do
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "coerces comma separated lists of features to a lowercase array on 2012+" do
+ node.automatic[:platform_version] = "6.2.9200"
+ resource.feature_name "SNMP, DHCP"
+ expect(resource.feature_name).to eql(%w{snmp dhcp})
+ end
+
+ it "coerces a single feature as a String to a lowercase array on 2012+" do
+ node.automatic[:platform_version] = "6.2.9200"
+ resource.feature_name "SNMP"
+ expect(resource.feature_name).to eql(["snmp"])
+ end
+
+ it "coerces comma separated lists of features to an array, but preserves case on < 2012" do
+ node.automatic[:platform_version] = "6.1.7601"
+ resource.feature_name "SNMP, DHCP"
+ expect(resource.feature_name).to eql(%w{SNMP DHCP})
+ end
+
+ it "coerces a single feature as a String to an array, but preserves case on < 2012" do
+ node.automatic[:platform_version] = "6.1.7601"
+ resource.feature_name "SNMP"
+ expect(resource.feature_name).to eql(["SNMP"])
+ end
+end
diff --git a/spec/unit/resource/windows_font_spec.rb b/spec/unit/resource/windows_font_spec.rb
new file mode 100644
index 0000000000..cd1050ea19
--- /dev/null
+++ b/spec/unit/resource/windows_font_spec.rb
@@ -0,0 +1,43 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsFont do
+ let(:resource) { Chef::Resource::WindowsFont.new("fakey_fakerton") }
+
+ it "sets resource name as :windows_font" do
+ expect(resource.resource_name).to eql(:windows_font)
+ end
+
+ it "the font_name property is the name_property" do
+ expect(resource.font_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install action" do
+ expect { resource.action :install }.not_to raise_error
+ end
+
+ it "coerces backslashes in the source property to forward slashes" do
+ resource.source 'C:\foo\bar\fontfile'
+ expect(resource.source).to eql("C:/foo/bar/fontfile")
+ end
+end
diff --git a/spec/unit/resource/windows_package_spec.rb b/spec/unit/resource/windows_package_spec.rb
index 5aa3707199..5a2cfcf99f 100644
--- a/spec/unit/resource/windows_package_spec.rb
+++ b/spec/unit/resource/windows_package_spec.rb
@@ -33,12 +33,22 @@ describe Chef::Resource::WindowsPackage, "initialize" do
let(:resource) { Chef::Resource::WindowsPackage.new("solitaire.msi") }
- it "returns a Chef::Resource::WindowsPackage" do
- expect(resource).to be_a_kind_of(Chef::Resource::WindowsPackage)
+ it "is a subclass of Chef::Resource::Package" do
+ expect(resource).to be_a_kind_of(Chef::Resource::Package)
end
- it "sets the resource_name to :windows_package" do
- expect(resource.resource_name).to eql(:windows_package)
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
end
it "supports setting installer_type as a symbol" do
@@ -88,7 +98,7 @@ describe Chef::Resource::WindowsPackage, "initialize" do
let(:resource_source) { "https://foo.bar/solitare.msi" }
let(:resource) { Chef::Resource::WindowsPackage.new(resource_source) }
- it "should return the source unmodified" do
+ it "returns the source unmodified" do
expect(resource.source).to eq(resource_source)
end
end
diff --git a/spec/unit/resource/windows_pagefile_spec.rb b/spec/unit/resource/windows_pagefile_spec.rb
new file mode 100644
index 0000000000..fff3cf3274
--- /dev/null
+++ b/spec/unit/resource/windows_pagefile_spec.rb
@@ -0,0 +1,49 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsPagefile do
+ let(:resource) { Chef::Resource::WindowsPagefile.new("C:\\pagefile.sys") }
+
+ it "sets resource name as :windows_pagefile" do
+ expect(resource.resource_name).to eql(:windows_pagefile)
+ end
+
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("C:\\pagefile.sys")
+ end
+
+ it "sets the default action as :set" do
+ expect(resource.action).to eql([:set])
+ end
+
+ it "supports :delete, :set actions" do
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :set }.not_to raise_error
+ end
+
+ it "coerces forward slashes in the path property to back slashes" do
+ resource.path "C:/pagefile.sys"
+ expect(resource.path).to eql("C:\\pagefile.sys")
+ end
+
+ it "automatic_managed property defaults to false" do
+ expect(resource.automatic_managed).to eql(false)
+ end
+
+end
diff --git a/spec/unit/resource/windows_path_spec.rb b/spec/unit/resource/windows_path_spec.rb
index aecea8ee6b..423d10aa61 100644
--- a/spec/unit/resource/windows_path_spec.rb
+++ b/spec/unit/resource/windows_path_spec.rb
@@ -19,20 +19,22 @@
require "spec_helper"
describe Chef::Resource::WindowsPath do
- subject { Chef::Resource::WindowsPath.new("some_path") }
-
- it { is_expected.to be_a_kind_of(Chef::Resource) }
- it { is_expected.to be_a_instance_of(Chef::Resource::WindowsPath) }
+ let(:resource) { Chef::Resource::WindowsPath.new("fakey_fakerton") }
it "sets resource name as :windows_path" do
- expect(subject.resource_name).to eql(:windows_path)
+ expect(resource.resource_name).to eql(:windows_path)
end
- it "sets the path as it's name" do
- expect(subject.path).to eql("some_path")
+ it "the path property is the name_property" do
+ expect(resource.path).to eql("fakey_fakerton")
end
it "sets the default action as :add" do
- expect(subject.action).to eql(:add)
+ expect(resource.action).to eql([:add])
+ end
+
+ it "supports :add, :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
end
end
diff --git a/spec/unit/resource/windows_printer_port_spec.rb b/spec/unit/resource/windows_printer_port_spec.rb
new file mode 100644
index 0000000000..a0267f81e2
--- /dev/null
+++ b/spec/unit/resource/windows_printer_port_spec.rb
@@ -0,0 +1,62 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsPrinterPort do
+ let(:resource) { Chef::Resource::WindowsPrinterPort.new("63.192.209.236") }
+
+ it "sets resource name as :windows_printer_port" do
+ expect(resource.resource_name).to eql(:windows_printer_port)
+ end
+
+ it "the ipv4_address property is the name_property" do
+ expect(resource.ipv4_address).to eql("63.192.209.236")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ end
+
+ it "port_number property defaults to 9100" do
+ expect(resource.port_number).to eql(9100)
+ end
+
+ it "snmp_enabled property defaults to false" do
+ expect(resource.snmp_enabled).to eql(false)
+ end
+
+ it "port_protocol property defaults to 1" do
+ expect(resource.port_protocol).to eql(1)
+ end
+
+ it "raises an error if port_protocol isn't in 1 or 2" do
+ expect { resource.port_protocol 1 }.not_to raise_error
+ expect { resource.port_protocol 2 }.not_to raise_error
+ expect { resource.port_protocol 3 }.to raise_error(ArgumentError)
+ end
+
+ it "raises an error if ipv4_address isn't in X.X.X.X format" do
+ expect { resource.ipv4_address "63.192.209.236" }.not_to raise_error
+ expect { resource.ipv4_address "a.b.c.d" }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/windows_printer_spec.rb b/spec/unit/resource/windows_printer_spec.rb
new file mode 100644
index 0000000000..107bde6296
--- /dev/null
+++ b/spec/unit/resource/windows_printer_spec.rb
@@ -0,0 +1,52 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsPrinter do
+ let(:resource) { Chef::Resource::WindowsPrinter.new("fakey_fakerton") }
+
+ it "sets resource name as :windows_printer" do
+ expect(resource.resource_name).to eql(:windows_printer)
+ end
+
+ it "the device_id property is the name_property" do
+ expect(resource.device_id).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create, :delete actions" do
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ end
+
+ it "default property defaults to false" do
+ expect(resource.default).to eql(false)
+ end
+
+ it "shared property defaults to false" do
+ expect(resource.shared).to eql(false)
+ end
+
+ it "raises an error if ipv4_address isn't in X.X.X.X format" do
+ expect { resource.ipv4_address "63.192.209.236" }.not_to raise_error
+ expect { resource.ipv4_address "a.b.c.d" }.to raise_error(ArgumentError)
+ end
+end
diff --git a/spec/unit/resource/windows_service_spec.rb b/spec/unit/resource/windows_service_spec.rb
index 2455a70f02..29f5821a15 100644
--- a/spec/unit/resource/windows_service_spec.rb
+++ b/spec/unit/resource/windows_service_spec.rb
@@ -27,16 +27,35 @@ describe Chef::Resource::WindowsService, "initialize" do
action: :start
)
- let(:resource) { Chef::Resource::WindowsService.new("BITS") }
-
- it "returns a Chef::Resource::WindowsService" do
- expect(resource).to be_a_kind_of(Chef::Resource::WindowsService)
- end
+ let(:resource) { Chef::Resource::WindowsService.new("fakey_fakerton") }
it "sets the resource_name to :windows_service" do
expect(resource.resource_name).to eql(:windows_service)
end
+ it "the service_name property is the name_property" do
+ expect(resource.service_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :nothing" do
+ expect(resource.action).to eql([:nothing])
+ end
+
+ it "supports :configure, :configure_startup, :create, :delete, :disable, :enable, :mask, :reload, :restart, :start, :stop, :unmask actions" do
+ expect { resource.action :configure }.not_to raise_error
+ expect { resource.action :configure_startup }.not_to raise_error
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :disable }.not_to raise_error
+ expect { resource.action :enable }.not_to raise_error
+ expect { resource.action :mask }.not_to raise_error
+ expect { resource.action :reload }.not_to raise_error
+ expect { resource.action :restart }.not_to raise_error
+ expect { resource.action :start }.not_to raise_error
+ expect { resource.action :stop }.not_to raise_error
+ expect { resource.action :unmask }.not_to raise_error
+ end
+
it "supports setting startup_type" do
resource.startup_type(:manual)
expect(resource.startup_type).to eql(:manual)
@@ -46,4 +65,29 @@ describe Chef::Resource::WindowsService, "initialize" do
resource.action :configure_startup
expect(resource.action).to eq([:configure_startup])
end
+
+ # Attributes that are Strings
+ %i{description service_name binary_path_name load_order_group dependencies
+ run_as_user run_as_password display_name}.each do |prop|
+ it "support setting #{prop}" do
+ resource.send("#{prop}=", "some value")
+ expect(resource.send(prop)).to eq("some value")
+ end
+ end
+
+ # Attributes that are Integers
+ %i{desired_access error_control service_type}.each do |prop|
+ it "support setting #{prop}" do
+ resource.send("#{prop}=", 1)
+ expect(resource.send(prop)).to eq(1)
+ end
+ end
+
+ # Attributes that are Booleans
+ %i{delayed_start}.each do |prop|
+ it "support setting #{prop}" do
+ resource.send("#{prop}=", true)
+ expect(resource.send(prop)).to eq(true)
+ end
+ end
end
diff --git a/spec/unit/resource/windows_shortcut_spec.rb b/spec/unit/resource/windows_shortcut_spec.rb
new file mode 100644
index 0000000000..cb32ab91bb
--- /dev/null
+++ b/spec/unit/resource/windows_shortcut_spec.rb
@@ -0,0 +1,38 @@
+#
+# Copyright:: Copyright 2018, Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+
+describe Chef::Resource::WindowsShortcut do
+ let(:resource) { Chef::Resource::WindowsShortcut.new("fakey_fakerton") }
+
+ it "sets resource name as :windows_shortcut" do
+ expect(resource.resource_name).to eql(:windows_shortcut)
+ end
+
+ it "the shortcut_name property is the name_property" do
+ expect(resource.shortcut_name).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :create action" do
+ expect { resource.action :create }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/windows_task_spec.rb b/spec/unit/resource/windows_task_spec.rb
index 2b3ee16024..6dbda35274 100644
--- a/spec/unit/resource/windows_task_spec.rb
+++ b/spec/unit/resource/windows_task_spec.rb
@@ -18,24 +18,19 @@
require "spec_helper"
-describe Chef::Resource::WindowsTask do
+describe Chef::Resource::WindowsTask, :windows_only do
let(:resource) { Chef::Resource::WindowsTask.new("sample_task") }
- it "creates a new Chef::Resource::WindowsTask" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_instance_of(Chef::Resource::WindowsTask)
- end
-
it "sets resource name as :windows_task" do
expect(resource.resource_name).to eql(:windows_task)
end
- it "sets the task_name as it's name" do
+ it "sets the task_name as its name" do
expect(resource.task_name).to eql("sample_task")
end
it "sets the default action as :create" do
- expect(resource.action).to eql(:create)
+ expect(resource.action).to eql([:create])
end
it "sets the default user as System" do
@@ -58,68 +53,159 @@ describe Chef::Resource::WindowsTask do
expect(resource.frequency_modifier).to eql(1)
end
- it "sets the default frequency as :hourly" do
- expect(resource.frequency).to eql(:hourly)
+ context "when frequency is not provided" do
+ it "raises ArgumentError to provide frequency" do
+ expect { resource.after_created }.to raise_error(ArgumentError, "Frequency needs to be provided. Valid frequencies are :minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :on_idle, :none." )
+ end
+ end
+
+ context "when user is set but password is not" do
+ before do
+ resource.frequency :hourly
+ end
+ it "raises an error if the user is a non-system user" do
+ resource.user "bob"
+ expect { resource.after_created }.to raise_error(ArgumentError, %q{Cannot specify a user other than the system users without specifying a password!. Valid passwordless users: 'NT AUTHORITY\SYSTEM', 'SYSTEM', 'NT AUTHORITY\LOCALSERVICE', 'NT AUTHORITY\NETWORKSERVICE', 'BUILTIN\USERS', 'USERS'})
+ end
+
+ it "does not raise an error if the user is a system user" do
+ resource.user 'NT AUTHORITY\SYSTEM'
+ expect { resource.after_created }.to_not raise_error
+ end
+
+ it "does not raise an error if the user is a system user even if lowercase" do
+ resource.user 'nt authority\system'
+ expect { resource.after_created }.to_not raise_error
+ end
end
context "when random_delay is passed" do
- it "raises error if frequency is `:once`" do
+ # changed this sepc since random_delay property is valid with it frequency :once
+ it "not raises error if frequency is `:once`" do
resource.frequency :once
resource.random_delay "20"
- expect { resource.after_created }.to raise_error(Chef::Exceptions::ArgumentError, "`random_delay` property is supported only for frequency :minute, :hourly, :daily, :weekly and :monthly")
+ resource.start_time "15:00"
+ expect { resource.after_created }.to_not raise_error(ArgumentError, "`random_delay` property is supported only for frequency :once, :minute, :hourly, :daily, :weekly and :monthly")
end
it "raises error for invalid random_delay" do
resource.frequency :monthly
resource.random_delay "xyz"
- expect { resource.after_created }.to raise_error(Chef::Exceptions::ArgumentError, "Invalid value passed for `random_delay`. Please pass seconds as a String e.g. '60'.")
+ expect { resource.after_created }.to raise_error(ArgumentError, "Invalid value passed for `random_delay`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60').")
+ end
+
+ it "raises error for invalid random_delay which looks like an Integer" do
+ resource.frequency :monthly
+ resource.random_delay "5,000"
+ expect { resource.after_created }.to raise_error(ArgumentError, "Invalid value passed for `random_delay`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60').")
end
- it "converts seconds into iso8601 format" do
+ it "converts '60' seconds into integer 1 minute format" do
resource.frequency :monthly
resource.random_delay "60"
resource.after_created
- expect(resource.random_delay).to eq("PT60S")
+ expect(resource.random_delay).to eq(1)
+ end
+
+ it "converts 60 Integer into integer 1 minute format" do
+ resource.frequency :monthly
+ resource.random_delay 60
+ resource.after_created
+ expect(resource.random_delay).to eq(1)
+ end
+
+ it "raises error that random_delay is not supported" do
+ expect { resource.send(:validate_random_delay, 60, :on_idle) }.to raise_error(ArgumentError, "`random_delay` property is supported only for frequency :once, :minute, :hourly, :daily, :weekly and :monthly")
end
end
- context "when execution_time_limit is passed" do
- it "sets the deafult value as PT72H" do
+ context "when execution_time_limit isn't specified" do
+ it "sets the default value to PT72H which get converted to minute as 4320" do
+ resource.frequency :hourly
resource.after_created
- expect(resource.execution_time_limit).to eq("PT72H")
+ expect(resource.execution_time_limit).to eq(4320)
end
+ end
+ context "when execution_time_limit is passed" do
it "raises error for invalid execution_time_limit" do
resource.execution_time_limit "abc"
- expect { resource.after_created }.to raise_error(Chef::Exceptions::ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as a String e.g. '60'.")
+ expect { resource.after_created }.to raise_error(ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60').")
+ end
+
+ it "raises error for invalid execution_time_limit that looks like an Integer" do
+ resource.execution_time_limit "5,000"
+ expect { resource.after_created }.to raise_error(ArgumentError, "Invalid value passed for `execution_time_limit`. Please pass seconds as an Integer (e.g. 60) or a String with numeric values only (e.g. '60').")
end
- it "converts seconds into iso8601 format" do
+ it "converts seconds Integer into integer minute format" do
+ resource.frequency :hourly
+ resource.execution_time_limit 60
+ resource.after_created
+ expect(resource.execution_time_limit).to eq(1)
+ end
+
+ it "converts seconds String into integer minute format" do
+ resource.frequency :hourly
resource.execution_time_limit "60"
resource.after_created
- expect(resource.execution_time_limit).to eq("PT60S")
+ expect(resource.execution_time_limit).to eq(1)
end
end
context "#validate_start_time" do
- it "raises error if start_time is nil" do
- expect { resource.send(:validate_start_time, nil) }.to raise_error(Chef::Exceptions::ArgumentError, "`start_time` needs to be provided with `frequency :once`")
+ it "raises error if start_time is nil when frequency `:once`" do
+ resource.frequency :once
+ expect { resource.send(:validate_start_time, nil, :once) }.to raise_error(ArgumentError, "`start_time` needs to be provided with `frequency :once`")
+ end
+
+ it "raises error if start_time is given when frequency `:none`" do
+ resource.frequency :none
+ expect { resource.send(:validate_start_time, "12.00", :none) }.to raise_error(ArgumentError, "`start_time` property is not supported with `frequency :none`")
+ end
+
+ it "raises error if start_time is not HH:mm format" do
+ resource.frequency :once
+ expect { resource.send(:validate_start_time, "2:30", :once) }.to raise_error(ArgumentError, "`start_time` property must be in the HH:mm format (e.g. 6:20pm -> 18:20).")
+ end
+
+ it "does not raise error if start_time is in HH:mm format" do
+ resource.frequency :once
+ expect { resource.send(:validate_start_time, "12:30", :once) }.not_to raise_error
end
end
context "#validate_start_day" do
- it "raise error if start_day is passed with frequency :on_logon" do
- resource.frequency :on_logon
- expect { resource.send(:validate_start_day, "Wed", :on_logon) }.to raise_error(Chef::Exceptions::ArgumentError, "`start_day` property is not supported with frequency: on_logon")
+ it "not to raise error if start_day is passed with invalid frequency (:onstart)" do
+ expect { resource.send(:validate_start_day, "02/07/1984", :onstart) }.not_to raise_error
end
- end
- context "#validate_user_and_password" do
- context "when password is not passed" do
- it "raises error with non-system users" do
- allow(resource).to receive(:use_password?).and_return(true)
- expect { resource.send(:validate_user_and_password, "Testuser", nil) }.to raise_error("Can't specify a non-system user without a password!")
- end
+ it "not to raise error if start_day is passed with invalid frequency (:on_idle)" do
+ expect { resource.send(:validate_start_day, "02/07/1984", :on_idle) }.not_to raise_error
+ end
+
+ it "not to raise error if start_day is passed with invalid frequency (:on_logon)" do
+ expect { resource.send(:validate_start_day, "02/07/1984", :on_logon) }.not_to raise_error
+ end
+
+ it "not raise error if start_day is passed with valid frequency (:weekly)" do
+ expect { resource.send(:validate_start_day, "02/07/1984", :weekly) }.not_to raise_error
+ end
+
+ it "not to raise error if start_day is passed with invalid date format (DD/MM/YYYY)" do
+ expect { resource.send(:validate_start_day, "28/12/2009", :weekly) }.to raise_error(ArgumentError, "`start_day` property must be in the MM/DD/YYYY format.")
+ end
+
+ it "raise error if start_day is passed with invalid date format (M/DD/YYYY)" do
+ expect { resource.send(:validate_start_day, "2/07/1984", :weekly) }.to raise_error(ArgumentError, "`start_day` property must be in the MM/DD/YYYY format.")
+ end
+
+ it "raise error if start_day is passed with invalid date format (MM/D/YYYY)" do
+ expect { resource.send(:validate_start_day, "02/7/1984", :weekly) }.to raise_error(ArgumentError, "`start_day` property must be in the MM/DD/YYYY format.")
+ end
+
+ it "raise error if start_day is passed with invalid date format (MM/DD/YY)" do
+ expect { resource.send(:validate_start_day, "02/07/84", :weekly) }.to raise_error(ArgumentError, "`start_day` property must be in the MM/DD/YYYY format.")
end
end
@@ -132,82 +218,119 @@ describe Chef::Resource::WindowsTask do
context "#validate_create_frequency_modifier" do
context "when frequency is :minute" do
it "raises error if frequency_modifier > 1439" do
- expect { resource.send(:validate_create_frequency_modifier, :minute, 1500) }.to raise_error("frequency_modifier value 1500 is invalid. Valid values for :minute frequency are 1 - 1439.")
+ expect { resource.send(:validate_create_frequency_modifier, :minute, 1500) }.to raise_error("frequency_modifier value 1500 is invalid. Valid values for :minute frequency are 1 - 1439.")
end
end
context "when frequency is :hourly" do
it "raises error if frequency_modifier > 23" do
- expect { resource.send(:validate_create_frequency_modifier, :hourly, 24) }.to raise_error("frequency_modifier value 24 is invalid. Valid values for :hourly frequency are 1 - 23.")
+ expect { resource.send(:validate_create_frequency_modifier, :hourly, 24) }.to raise_error("frequency_modifier value 24 is invalid. Valid values for :hourly frequency are 1 - 23.")
end
end
context "when frequency is :daily" do
it "raises error if frequency_modifier > 365" do
- expect { resource.send(:validate_create_frequency_modifier, :daily, 366) }.to raise_error("frequency_modifier value 366 is invalid. Valid values for :daily frequency are 1 - 365.")
+ expect { resource.send(:validate_create_frequency_modifier, :daily, 366) }.to raise_error("frequency_modifier value 366 is invalid. Valid values for :daily frequency are 1 - 365.")
end
end
context "when frequency is :weekly" do
it "raises error if frequency_modifier > 52" do
- expect { resource.send(:validate_create_frequency_modifier, :weekly, 53) }.to raise_error("frequency_modifier value 53 is invalid. Valid values for :weekly frequency are 1 - 52.")
+ expect { resource.send(:validate_create_frequency_modifier, :weekly, 53) }.to raise_error("frequency_modifier value 53 is invalid. Valid values for :weekly frequency are 1 - 52.")
end
end
context "when frequency is :monthly" do
it "raises error if frequency_modifier > 12" do
- expect { resource.send(:validate_create_frequency_modifier, :monthly, 14) }.to raise_error("frequency_modifier value 14 is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', 'LASTDAY'.")
+ expect { resource.send(:validate_create_frequency_modifier, :monthly, 14) }.to raise_error("frequency_modifier value 14 is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
end
it "raises error if frequency_modifier is invalid" do
- expect { resource.send(:validate_create_frequency_modifier, :monthly, "abc") }.to raise_error("frequency_modifier value abc is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', 'LASTDAY'.")
+ expect { resource.send(:validate_create_frequency_modifier, :monthly, "abc") }.to raise_error("frequency_modifier value abc is invalid. Valid values for :monthly frequency are 1 - 12, 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST'.")
end
end
end
context "#validate_create_day" do
it "raises error if frequency is not :weekly or :monthly" do
- expect { resource.send(:validate_create_day, "Mon", :once) }.to raise_error("day attribute is only valid for tasks that run monthly or weekly")
+ expect { resource.send(:validate_create_day, "Mon", :once, 1) }.to raise_error("day property is only valid for tasks that run monthly or weekly")
end
it "accepts a valid single day" do
- expect { resource.send(:validate_create_day, "Mon", :weekly) }.not_to raise_error
+ expect { resource.send(:validate_create_day, "Mon", :weekly, 1) }.not_to raise_error
end
it "accepts a comma separated list of valid days" do
- expect { resource.send(:validate_create_day, "Mon, tue, THU", :weekly) }.not_to raise_error
+ expect { resource.send(:validate_create_day, "Mon, tue, THU", :weekly, 1) }.not_to raise_error
end
it "raises error for invalid day value" do
- expect { resource.send(:validate_create_day, "xyz", :weekly) }.to raise_error("day attribute invalid. Only valid values are: MON, TUE, WED, THU, FRI, SAT, SUN and *. Multiple values must be separated by a comma.")
+ expect { resource.send(:validate_create_day, "xyz", :weekly, 1) }.to raise_error(ArgumentError, "day property invalid. Only valid values are: MON, TUE, WED, THU, FRI, SAT, SUN, *. Multiple values must be separated by a comma.")
end
end
context "#validate_create_months" do
it "raises error if frequency is not :monthly" do
- expect { resource.send(:validate_create_months, "Jan", :once) }.to raise_error("months attribute is only valid for tasks that run monthly")
+ expect { resource.send(:validate_create_months, "Jan", :once) }.to raise_error(ArgumentError, "months property is only valid for tasks that run monthly")
end
it "accepts a valid single month" do
- expect { resource.send(:validate_create_months, "Feb", :monthly) }.not_to raise_error
+ expect { resource.send(:validate_create_months, "Feb", :monthly) }.not_to raise_error
end
it "accepts a comma separated list of valid months" do
- expect { resource.send(:validate_create_months, "Jan, mar, AUG", :monthly) }.not_to raise_error
+ expect { resource.send(:validate_create_months, "Jan, mar, AUG", :monthly) }.not_to raise_error
end
it "raises error for invalid month value" do
- expect { resource.send(:validate_create_months, "xyz", :monthly) }.to raise_error("months attribute invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC and *. Multiple values must be separated by a comma.")
+ expect { resource.send(:validate_create_months, "xyz", :monthly) }.to raise_error(ArgumentError, "months property invalid. Only valid values are: JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC, *. Multiple values must be separated by a comma.")
end
end
context "#validate_idle_time" do
it "raises error if frequency is not :on_idle" do
- expect { resource.send(:validate_idle_time, 5, :hourly) }.to raise_error("idle_time attribute is only valid for tasks that run on_idle")
+ [:minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :none].each do |frequency|
+ expect { resource.send(:validate_idle_time, 5, frequency) }.to raise_error(ArgumentError, "idle_time property is only valid for tasks that run on_idle")
+ end
end
it "raises error if idle_time > 999" do
- expect { resource.send(:validate_idle_time, 1000, :on_idle) }.to raise_error("idle_time value 1000 is invalid. Valid values for :on_idle frequency are 1 - 999.")
+ expect { resource.send(:validate_idle_time, 1000, :on_idle) }.to raise_error(ArgumentError, "idle_time value 1000 is invalid. Valid values for :on_idle frequency are 1 - 999.")
+ end
+
+ it "raises error if idle_time < 0" do
+ expect { resource.send(:validate_idle_time, -5, :on_idle) }.to raise_error(ArgumentError, "idle_time value -5 is invalid. Valid values for :on_idle frequency are 1 - 999.")
+ end
+
+ it "raises error if idle_time is not set" do
+ expect { resource.send(:validate_idle_time, nil, :on_idle) }.to raise_error(ArgumentError, "idle_time value should be set for :on_idle frequency.")
+ end
+
+ it "does not raises error if idle_time is not set for other frequencies" do
+ [:minute, :hourly, :daily, :weekly, :monthly, :once, :on_logon, :onstart, :none].each do |frequency|
+ expect { resource.send(:validate_idle_time, nil, frequency) }.not_to raise_error
+ end
+ end
+ end
+
+ context "#sec_to_dur" do
+ it "return nil when passed 0" do
+ expect(resource.send(:sec_to_dur, 0)).to eql("PT0S")
+ end
+ it "return PT1S when passed 1" do
+ expect(resource.send(:sec_to_dur, 1)).to eql("PT1S")
+ end
+ it "return PT86400S when passed 86400" do
+ expect(resource.send(:sec_to_dur, 86400)).to eql("PT86400S")
+ end
+ it "return PT86401S when passed 86401" do
+ expect(resource.send(:sec_to_dur, 86401)).to eql("PT86401S")
+ end
+ it "return PT86500S when passed 86500" do
+ expect(resource.send(:sec_to_dur, 86500)).to eql("PT86500S")
+ end
+ it "return PT604801S when passed 604801" do
+ expect(resource.send(:sec_to_dur, 604801)).to eql("PT604801S")
end
end
end
diff --git a/spec/unit/resource/yum_package_spec.rb b/spec/unit/resource/yum_package_spec.rb
index a1e8417e0e..d1dc1a3cce 100644
--- a/spec/unit/resource/yum_package_spec.rb
+++ b/spec/unit/resource/yum_package_spec.rb
@@ -78,7 +78,7 @@ describe Chef::Resource::YumPackage, "arch" do
@resource = Chef::Resource::YumPackage.new("foo")
end
- it "should set the arch variable to whatever is passed in" do
+ it "sets the arch variable to whatever is passed in" do
@resource.arch("i386")
expect(@resource.arch).to eql("i386")
end
@@ -90,19 +90,19 @@ describe Chef::Resource::YumPackage, "flush_cache" do
end
it "should default the flush timing to false" do
- flush_hash = { :before => false, :after => false }
+ flush_hash = { before: false, after: false }
expect(@resource.flush_cache).to eq(flush_hash)
end
it "should allow you to set the flush timing with an array" do
flush_array = [ :before, :after ]
- flush_hash = { :before => true, :after => true }
+ flush_hash = { before: true, after: true }
@resource.flush_cache(flush_array)
expect(@resource.flush_cache).to eq(flush_hash)
end
it "should allow you to set the flush timing with a hash" do
- flush_hash = { :before => true, :after => true }
+ flush_hash = { before: true, after: true }
@resource.flush_cache(flush_hash)
expect(@resource.flush_cache).to eq(flush_hash)
end
diff --git a/spec/unit/resource/yum_repository_spec.rb b/spec/unit/resource/yum_repository_spec.rb
index afd6c6739a..13301dca69 100644
--- a/spec/unit/resource/yum_repository_spec.rb
+++ b/spec/unit/resource/yum_repository_spec.rb
@@ -22,27 +22,130 @@ describe Chef::Resource::YumRepository do
let(:node) { Chef::Node.new }
let(:events) { Chef::EventDispatch::Dispatcher.new }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
- let(:resource) { Chef::Resource::YumRepository.new("multiverse", run_context) }
+ let(:resource) { Chef::Resource::YumRepository.new("fakey_fakerton", run_context) }
- context "on linux", :linux_only do
- it "should create a new Chef::Resource::YumRepository" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::YumRepository)
- end
+ it "has a resource_name of :yum_repository" do
+ expect(resource.resource_name).to eq(:yum_repository)
+ end
+
+ it "the repositoryid property is the name_property" do
+ expect(resource.repositoryid).to eql("fakey_fakerton")
+ end
+
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
+
+ it "supports :add, :create, :delete, :makecache, :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :delete }.not_to raise_error
+ expect { resource.action :makecache }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "fails if the user provides a repositoryid with a forward slash" do
+ expect { resource.repositoryid "foo/bar" }.to raise_error(ArgumentError)
+ end
+
+ it "clean_headers property defaults to false" do
+ expect(resource.clean_headers).to eql(false)
+ end
+
+ it "clean_metadata property defaults to true" do
+ expect(resource.clean_metadata).to eql(true)
+ end
+
+ it "description property defaults to 'Yum Repository'" do
+ expect(resource.description).to eql("Yum Repository")
+ end
+
+ it "enabled property defaults to true" do
+ expect(resource.enabled).to eql(true)
+ end
+
+ it "make_cache property defaults to true" do
+ expect(resource.make_cache).to eql(true)
+ end
- it "should resolve to a Noop class when yum is not found" do
+ it "mode property defaults to '0644'" do
+ expect(resource.mode).to eql("0644")
+ end
+
+ it "the timeout property expects numeric Strings" do
+ expect { resource.timeout "123" }.not_to raise_error(ArgumentError)
+ expect { resource.timeout "123foo" }.to raise_error(ArgumentError)
+ end
+
+ it "the priority property expects numeric Strings from '1' to '99'" do
+ expect { resource.priority "99" }.not_to raise_error(ArgumentError)
+ expect { resource.priority "1" }.not_to raise_error(ArgumentError)
+ expect { resource.priority "100" }.to raise_error(ArgumentError)
+ expect { resource.priority "0" }.to raise_error(ArgumentError)
+ end
+
+ it "the failovermethod property accepts 'priority' or 'roundrobin'" do
+ expect { resource.failovermethod "priority" }.not_to raise_error(ArgumentError)
+ expect { resource.failovermethod "roundrobin" }.not_to raise_error(ArgumentError)
+ expect { resource.failovermethod "bob" }.to raise_error(ArgumentError)
+ end
+
+ it "the http_caching property accepts 'packages', 'all', or 'none'" do
+ expect { resource.http_caching "packages" }.not_to raise_error(ArgumentError)
+ expect { resource.http_caching "all" }.not_to raise_error(ArgumentError)
+ expect { resource.http_caching "none" }.not_to raise_error(ArgumentError)
+ expect { resource.http_caching "bob" }.to raise_error(ArgumentError)
+ end
+
+ it "the metadata_expire property accepts a time value or 'never'" do
+ expect { resource.metadata_expire "100" }.not_to raise_error(ArgumentError)
+ expect { resource.metadata_expire "100d" }.not_to raise_error(ArgumentError)
+ expect { resource.metadata_expire "100h" }.not_to raise_error(ArgumentError)
+ expect { resource.metadata_expire "100m" }.not_to raise_error(ArgumentError)
+ expect { resource.metadata_expire "never" }.not_to raise_error(ArgumentError)
+ expect { resource.metadata_expire "100s" }.to raise_error(ArgumentError)
+ end
+
+ it "the mirror_expire property accepts a time value" do
+ expect { resource.mirror_expire "100" }.not_to raise_error(ArgumentError)
+ expect { resource.mirror_expire "100d" }.not_to raise_error(ArgumentError)
+ expect { resource.mirror_expire "100h" }.not_to raise_error(ArgumentError)
+ expect { resource.mirror_expire "100m" }.not_to raise_error(ArgumentError)
+ expect { resource.mirror_expire "never" }.to raise_error(ArgumentError)
+ end
+
+ it "the mirrorlist_expire property accepts a time value" do
+ expect { resource.mirrorlist_expire "100" }.not_to raise_error(ArgumentError)
+ expect { resource.mirrorlist_expire "100d" }.not_to raise_error(ArgumentError)
+ expect { resource.mirrorlist_expire "100h" }.not_to raise_error(ArgumentError)
+ expect { resource.mirrorlist_expire "100m" }.not_to raise_error(ArgumentError)
+ expect { resource.mirrorlist_expire "never" }.to raise_error(ArgumentError)
+ end
+
+ it "accepts the legacy 'url' property" do
+ resource.url "foo"
+ expect(resource.baseurl).to eql("foo")
+ end
+
+ it "accepts the legacy 'keyurl' property" do
+ resource.keyurl "foo"
+ expect(resource.gpgkey).to eql("foo")
+ end
+
+ context "on linux", :linux_only do
+ it "resolves to a Noop class when yum is not found" do
expect(Chef::Provider::YumRepository).to receive(:which).with("yum").and_return(false)
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a YumRepository class when yum is found" do
+ it "resolves to a YumRepository class when yum is found" do
expect(Chef::Provider::YumRepository).to receive(:which).with("yum").and_return(true)
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::YumRepository)
end
end
context "on windows", :windows_only do
- it "should resolve to a NoOp provider" do
+ it "resolves to a NoOp provider" do
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
end
diff --git a/spec/unit/resource/zypper_package_spec.rb b/spec/unit/resource/zypper_package_spec.rb
new file mode 100644
index 0000000000..fff2fd2a59
--- /dev/null
+++ b/spec/unit/resource/zypper_package_spec.rb
@@ -0,0 +1,51 @@
+#
+# Author:: Tim Smith (<tsmith@chef.io>)
+# Copyright:: Copyright 2018 Chef Software, Inc.
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "support/shared/unit/resource/static_provider_resolution"
+
+describe Chef::Resource::ZypperPackage, "initialize" do
+
+ static_provider_resolution(
+ resource: Chef::Resource::ZypperPackage,
+ provider: Chef::Provider::Package::Zypper,
+ name: :zypper_package,
+ action: :install,
+ os: "linux",
+ platform_family: "suse"
+ )
+
+end
+
+describe Chef::Resource::ZypperPackage, "defaults" do
+ let(:resource) { Chef::Resource::ZypperPackage.new("fakey_fakerton") }
+
+ it "sets the default action as :install" do
+ expect(resource.action).to eql([:install])
+ end
+
+ it "supports :install, :lock, :purge, :reconfig, :remove, :unlock, :upgrade actions" do
+ expect { resource.action :install }.not_to raise_error
+ expect { resource.action :lock }.not_to raise_error
+ expect { resource.action :purge }.not_to raise_error
+ expect { resource.action :reconfig }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ expect { resource.action :unlock }.not_to raise_error
+ expect { resource.action :upgrade }.not_to raise_error
+ end
+end
diff --git a/spec/unit/resource/zypper_repository_spec.rb b/spec/unit/resource/zypper_repository_spec.rb
index 16951d071c..a6a523a33f 100644
--- a/spec/unit/resource/zypper_repository_spec.rb
+++ b/spec/unit/resource/zypper_repository_spec.rb
@@ -22,44 +22,94 @@ describe Chef::Resource::ZypperRepository do
let(:node) { Chef::Node.new }
let(:events) { Chef::EventDispatch::Dispatcher.new }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
- let(:resource) { Chef::Resource::ZypperRepository.new("repo-source", run_context) }
+ let(:resource) { Chef::Resource::ZypperRepository.new("fakey_fakerton", run_context) }
- context "on linux", :linux_only do
- it "should create a new Chef::Resource::ZypperRepository" do
- expect(resource).to be_a_kind_of(Chef::Resource)
- expect(resource).to be_a_kind_of(Chef::Resource::ZypperRepository)
- end
+ it "has a resource_name of :zypper_repository" do
+ expect(resource.resource_name).to eq(:zypper_repository)
+ end
- it "should have a name of repo-source" do
- expect(resource.name).to eql("repo-source")
- end
+ it "the repo_name property is the name_property" do
+ expect(resource.repo_name).to eql("fakey_fakerton")
+ end
- it "should have a default action of create" do
- expect(resource.action).to eql([:create])
- end
+ it "sets the default action as :create" do
+ expect(resource.action).to eql([:create])
+ end
- it "supports all valid actions" do
- expect { resource.action :add }.not_to raise_error
- expect { resource.action :remove }.not_to raise_error
- expect { resource.action :create }.not_to raise_error
- expect { resource.action :refresh }.not_to raise_error
- expect { resource.action :delete }.to raise_error(ArgumentError)
- end
+ it "supports :add, :create, :refresh, :remove actions" do
+ expect { resource.action :add }.not_to raise_error
+ expect { resource.action :create }.not_to raise_error
+ expect { resource.action :refresh }.not_to raise_error
+ expect { resource.action :remove }.not_to raise_error
+ end
+
+ it "fails if the user provides a repo_name with a forward slash" do
+ expect { resource.repo_name "foo/bar" }.to raise_error(ArgumentError)
+ end
+
+ it "type property defaults to 'NONE'" do
+ expect(resource.type).to eql("NONE")
+ end
+
+ it "enabled property defaults to true" do
+ expect(resource.enabled).to eql(true)
+ end
- it "should resolve to a Noop class when zypper is not found" do
- expect(Chef::Provider::ZypperRepository).to receive(:which).with("zypper").and_return(false)
+ it "autorefresh property defaults to true" do
+ expect(resource.autorefresh).to eql(true)
+ end
+
+ it "gpgcheck property defaults to true" do
+ expect(resource.gpgcheck).to eql(true)
+ end
+
+ it "keeppackages property defaults to false" do
+ expect(resource.keeppackages).to eql(false)
+ end
+
+ it "priority property defaults to 99" do
+ expect(resource.priority).to eql(99)
+ end
+
+ it "mode property defaults to '0644'" do
+ expect(resource.mode).to eql("0644")
+ end
+
+ it "refresh_cache property defaults to true" do
+ expect(resource.refresh_cache).to eql(true)
+ end
+
+ it "gpgautoimportkeys property defaults to true" do
+ expect(resource.gpgautoimportkeys).to eql(true)
+ end
+
+ it "accepts the legacy 'key' property" do
+ resource.key "foo"
+ expect(resource.gpgkey).to eql("foo")
+ end
+
+ it "accepts the legacy 'uri' property" do
+ resource.uri "foo"
+ expect(resource.baseurl).to eql("foo")
+ end
+
+ context "on linux", :linux_only do
+ it "resolves to a Noop class when on non-linux OS" do
+ node.automatic[:os] = "windows"
+ node.automatic[:platform_family] = "windows"
expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- it "should resolve to a ZypperRepository class when zypper is found" do
- expect(Chef::Provider::ZypperRepository).to receive(:which).with("zypper").and_return(true)
- expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::ZypperRepository)
+ it "resolves to a Noop class when on non-suse linux" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "debian"
+ expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
end
- end
- context "on windows", :windows_only do
- it "should resolve to a NoOp provider" do
- expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::Noop)
+ it "resolves to a ZypperRepository class when on a suse platform_family" do
+ node.automatic[:os] = "linux"
+ node.automatic[:platform_family] = "suse"
+ expect(resource.provider_for_action(:add)).to be_a(Chef::Provider::ZypperRepository)
end
end
end
diff --git a/spec/unit/resource_collection/resource_set_spec.rb b/spec/unit/resource_collection/resource_set_spec.rb
index 9955bc2bea..403be4c566 100644
--- a/spec/unit/resource_collection/resource_set_spec.rb
+++ b/spec/unit/resource_collection/resource_set_spec.rb
@@ -73,25 +73,25 @@ describe Chef::ResourceCollection::ResourceSet do
it "should find a resource by type symbol and name" do
collection.insert_as(zen_master)
- expect(collection.find(:zen_master => zen_master_name)).to equal(zen_master)
+ expect(collection.find(zen_master: zen_master_name)).to equal(zen_master)
end
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 => %w{name1 name2}), zen_master_name, zen_master2_name)
+ check_by_names(collection.find( zzz: %w{name1 name2}), zen_master_name, zen_master2_name)
end
it "should find resources of multiple kinds (:zen_master => a, :zen_follower => b)" do
collection.insert_as(zen_master)
collection.insert_as(zen_follower)
- check_by_names(collection.find(:zen_master => [zen_master_name], :zen_follower => [zen_follower_name]),
+ check_by_names(collection.find(zen_master: [zen_master_name], zen_follower: [zen_follower_name]),
zen_master_name, zen_follower_name)
end
@@ -99,7 +99,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 => %w{name1 name2}, :yyy => ["name3"]),
+ check_by_names(collection.find(zzz: %w{name1 name2}, yyy: ["name3"]),
zen_master_name, zen_follower_name, zen_master2_name)
end
@@ -215,7 +215,7 @@ describe Chef::ResourceCollection::ResourceSet do
end
it "accepts a single-element :resource_type => 'resource_name' Hash" do
- expect(collection.validate_lookup_spec!(:service => "apache2")).to be_truthy
+ expect(collection.validate_lookup_spec!(service: "apache2")).to be_truthy
end
it "accepts a chef resource object" do
diff --git a/spec/unit/resource_collection_spec.rb b/spec/unit/resource_collection_spec.rb
index c696572b13..8dd367b0ec 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
@@ -196,19 +196,19 @@ describe Chef::ResourceCollection 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")
+ expect(rc.resources(zen_master: "monkey").name).to eql("monkey")
end
it "should find a resource by symbol and array of names (:zen_master => [a,b])" do
load_up_resources
- results = rc.resources(:zen_master => %w{monkey dog})
+ results = rc.resources(zen_master: %w{monkey dog})
expect(results.length).to eql(2)
check_by_names(results, "monkey", "dog")
end
it "should find resources of multiple kinds (:zen_master => a, :file => b)" do
load_up_resources
- results = rc.resources(:zen_master => "monkey", :file => "something")
+ results = rc.resources(zen_master: "monkey", file: "something")
expect(results.length).to eql(2)
check_by_names(results, "monkey", "something")
end
@@ -253,7 +253,7 @@ describe Chef::ResourceCollection do
end
it "accepts a single-element :resource_type => 'resource_name' Hash" do
- expect(rc.validate_lookup_spec!(:service => "apache2")).to be_truthy
+ expect(rc.validate_lookup_spec!(service: "apache2")).to be_truthy
end
it "accepts a chef resource object" do
diff --git a/spec/unit/resource_definition_spec.rb b/spec/unit/resource_definition_spec.rb
index cc19cc7a01..5be3e59009 100644
--- a/spec/unit/resource_definition_spec.rb
+++ b/spec/unit/resource_definition_spec.rb
@@ -66,13 +66,13 @@ describe Chef::ResourceDefinition do
it "should accept a new definition with a hash" do
expect do
- defn.define :smoke, :cigar => "cuban", :cigarette => "marlboro" do
+ defn.define :smoke, cigar: "cuban", cigarette: "marlboro" do
end
end.not_to raise_error
end
it "should expose the prototype hash params in the params hash" do
- defn.define(:smoke, :cigar => "cuban", :cigarette => "marlboro") {}
+ defn.define(:smoke, cigar: "cuban", cigarette: "marlboro") {}
expect(defn.params[:cigar]).to eql("cuban")
expect(defn.params[:cigarette]).to eql("marlboro")
end
diff --git a/spec/unit/resource_inspector_spec.rb b/spec/unit/resource_inspector_spec.rb
new file mode 100644
index 0000000000..aef92732b3
--- /dev/null
+++ b/spec/unit/resource_inspector_spec.rb
@@ -0,0 +1,60 @@
+# Copyright:: Copyright 2018, Chef Software, Inc
+# License:: Apache License, Version 2.0
+#
+# 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.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require "spec_helper"
+require "chef/resource_inspector"
+
+class DummyResource < Chef::Resource
+ resource_name :dummy
+ description "A dummy resource"
+ examples <<~EOH
+ dummy "foo" do
+ first "yes"
+ end
+ EOH
+ introduced "14.0"
+ property :first, String, description: "My First Property", introduced: "14.0"
+
+ action :dummy do
+ return true
+ end
+end
+
+describe ResourceInspector do
+ describe "inspecting a resource" do
+ subject { ResourceInspector.extract_resource(DummyResource, false) }
+
+ it "returns a hash with required data" do
+ expect(subject[:description]).to eq "A dummy resource"
+ expect(subject[:actions]).to match_array [:nothing, :dummy]
+ end
+
+ context "excluding built in properties" do
+ it "returns a single property" do
+ expect(subject[:properties].count).to eq 1
+ expect(subject[:properties].first[:name]).to eq :first
+ end
+ end
+
+ context "including built in properties" do
+ subject { ResourceInspector.extract_resource(DummyResource, true) }
+ it "returns many properties" do
+ expect(subject[:properties].count).to be > 1
+ expect(subject[:properties].map { |n| n[:name] }).to include(:name, :first, :sensitive)
+ end
+ end
+ end
+end
diff --git a/spec/unit/resource_reporter_spec.rb b/spec/unit/resource_reporter_spec.rb
index 4fcfb01233..fe8b129a73 100644
--- a/spec/unit/resource_reporter_spec.rb
+++ b/spec/unit/resource_reporter_spec.rb
@@ -42,7 +42,7 @@ describe Chef::ResourceReporter do
@new_resource = Chef::Resource::File.new("/tmp/a-file.txt")
@cookbook_name = "monkey"
@new_resource.cookbook_name = @cookbook_name
- @cookbook_version = double("Cookbook::Version", :version => "1.2.3")
+ @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")
@start_time = Time.new
@@ -285,7 +285,7 @@ describe Chef::ResourceReporter do
end
it "resource_command in prepared_run_data should be blank" do
- expect(@first_update_report["after"]).to eq({ :command => "sensitive-resource", :user => nil })
+ expect(@first_update_report["after"]).to eq({ command: "sensitive-resource" })
end
end
@@ -317,9 +317,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)
@@ -472,7 +472,7 @@ describe Chef::ResourceReporter do
context "when the resource is a RegistryKey with binary data" do
let(:new_resource) do
resource = Chef::Resource::RegistryKey.new('Wubba\Lubba\Dub\Dubs')
- resource.values([ { :name => "rick", :type => :binary, :data => 255.chr * 1 } ])
+ resource.values([ { name: "rick", type: :binary, data: 255.chr * 1 } ])
allow(resource).to receive(:cookbook_name).and_return(@cookbook_name)
allow(resource).to receive(:cookbook_version).and_return(@cookbook_version)
resource
@@ -480,7 +480,7 @@ describe Chef::ResourceReporter do
let(:current_resource) do
resource = Chef::Resource::RegistryKey.new('Wubba\Lubba\Dub\Dubs')
- resource.values([ { :name => "rick", :type => :binary, :data => 255.chr * 1 } ])
+ resource.values([ { name: "rick", type: :binary, data: 255.chr * 1 } ])
resource
end
@@ -616,11 +616,11 @@ describe Chef::ResourceReporter do
# 404 getting the run_id
@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 }).
- and_raise(@error)
+ 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 })
+ .and_raise(@error)
end
it "assumes the feature is not enabled" do
@@ -635,7 +635,7 @@ describe Chef::ResourceReporter do
end
it "prints an error about the 404" do
- expect(Chef::Log).to receive(:debug).with(/404/)
+ expect(Chef::Log).to receive(:trace).with(/404/)
@resource_reporter.run_started(@run_status)
end
@@ -646,10 +646,10 @@ describe Chef::ResourceReporter do
# 500 getting the run_id
@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 }).
- and_raise(@error)
+ 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 })
+ .and_raise(@error)
end
it "assumes the feature is not enabled" do
@@ -676,10 +676,10 @@ describe Chef::ResourceReporter do
# 500 getting the run_id
@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 }).
- and_raise(@error)
+ 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 })
+ .and_raise(@error)
end
after do
@@ -697,10 +697,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" }
- 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 }).
- and_return(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 })
+ .and_return(response)
@resource_reporter.run_started(@run_status)
end
diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb
index 9227c8b12d..a4f64e11e1 100644
--- a/spec/unit/resource_spec.rb
+++ b/spec/unit/resource_spec.rb
@@ -3,7 +3,7 @@
# Author:: Christopher Walters (<cw@chef.io>)
# Author:: Tim Hinderliter (<tim@chef.io>)
# Author:: Seth Chisamore (<schisamo@chef.io>)
-# Copyright:: Copyright 2008-2017, Chef Software Inc.
+# Copyright:: Copyright 2008-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -38,10 +38,6 @@ describe Chef::Resource do
expect(resource.respond_to?(:shell_out!)).to be true
end
- it "should mixin shell_out_with_systems_locale" do
- expect(resource.respond_to?(:shell_out_with_systems_locale)).to be true
- end
-
describe "when inherited" do
it "adds an entry to a list of subclasses" do
@@ -234,54 +230,54 @@ describe Chef::Resource do
describe "notifies" 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")
+ 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
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
+ 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
end
it "should raise an exception if told to act in other than :delay or :immediate(ly)" do
run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee")
expect do
- resource.notifies :reload, run_context.resource_collection.find(:zen_master => "coffee"), :someday
+ resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee"), :someday
end.to raise_error(ArgumentError)
end
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")
+ 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
run_context.resource_collection << Chef::Resource::ZenMaster.new("beans")
- resource.notifies :reload, run_context.resource_collection.find(:zen_master => "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
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)
+ resource.notifies(:restart, service: "apache")
+ 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)
+ resource.notifies_immediately(:restart, service: "apache")
+ 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)
+ resource.notifies_delayed(:restart, service: "apache")
+ 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(%w{coffee tea})
- resource.notifies :reload, run_context.resource_collection.find(:zen_master => "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
end
@@ -306,26 +302,26 @@ describe Chef::Resource do
describe "subscribes" do
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")
+ 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
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")
+ 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
run_context.resource_collection << Chef::Resource::ZenMaster.new("bean")
- zrb = run_context.resource_collection.find(:zen_master => "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
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")
+ 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
end
@@ -387,6 +383,37 @@ describe Chef::Resource do
end
end
+ context "Documentation of resources" do
+ it "can have a description" do
+ c = Class.new(Chef::Resource) do
+ description "my description"
+ end
+ expect(c.description).to eq "my description"
+ end
+
+ it "can say when it was introduced" do
+ c = Class.new(Chef::Resource) do
+ introduced "14.0"
+ end
+ expect(c.introduced).to eq "14.0"
+ end
+
+ it "can have some examples" do
+ c = Class.new(Chef::Resource) do
+ examples <<~EOH
+ resource "foo" do
+ foo foo
+ end
+ EOH
+ end
+ expect(c.examples).to eq <<~EOH
+ resource "foo" do
+ foo foo
+ end
+ EOH
+ end
+ end
+
describe "self.resource_name" do
context "When resource_name is not set" do
it "and there are no provides lines, resource_name is nil" do
@@ -525,9 +552,14 @@ describe Chef::Resource do
expect(resource.ignore_failure).to eq(true)
end
- it "should allow you to epic_fail" do
- resource.epic_fail(true)
- expect(resource.epic_fail).to eq(true)
+ it "should allow you to set quiet ignore_failure as a symbol" do
+ resource.ignore_failure(:quiet)
+ expect(resource.ignore_failure).to eq(:quiet)
+ end
+
+ it "should allow you to set quiet ignore_failure as a string" do
+ resource.ignore_failure("quiet")
+ expect(resource.ignore_failure).to eq("quiet")
end
end
@@ -643,7 +675,7 @@ describe Chef::Resource do
snitch_variable = nil
resource.only_if { snitch_variable = true }
expect(resource.only_if.first.positivity).to eq(:only_if)
- #Chef::Mixin::Command.should_receive(:only_if).with(true, {}).and_return(false)
+ # Chef::Mixin::Command.should_receive(:only_if).with(true, {}).and_return(false)
resource.run_action(:purr)
expect(snitch_variable).to be_truthy
end
@@ -659,8 +691,8 @@ 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" })
+ resource.only_if("true", cwd: "/tmp")
+ expect(resource.only_if.first.command_opts).to eq({ cwd: "/tmp" })
resource.run_action(:purr)
end
@@ -683,8 +715,8 @@ describe Chef::Resource do
end
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" })
+ resource.not_if("pwd" , cwd: "/tmp")
+ expect(resource.not_if.first.command_opts).to eq({ cwd: "/tmp" })
end
it "accepts multiple not_if conditionals" do
@@ -835,7 +867,7 @@ describe Chef::Resource do
snitch_var1 = snitch_var2 = 0
runner = Chef::Runner.new(run_context)
- Chef::Provider::SnakeOil.provides :cat
+ Chef::Provider::SnakeOil.provides :cat, __core_override__: true
resource1.only_if { snitch_var1 = 1 }
resource1.not_if { snitch_var2 = 2 }
@@ -919,7 +951,7 @@ describe Chef::Resource do
node.name("bumblebee")
node.automatic[:platform] = "autobots"
node.automatic[:platform_version] = "6.1"
- klz2.provides :dinobot, :platform => ["autobots"]
+ klz2.provides :dinobot, platform: ["autobots"]
Object.const_set("Grimlock", klz2)
klz2.provides :grimlock
end
@@ -1112,4 +1144,38 @@ describe Chef::Resource do
it { is_expected.to eq [:two, :one] }
end
end
+
+ describe ".preview_resource" do
+ let(:klass) { Class.new(Chef::Resource) }
+
+ before do
+ allow(Chef::DSL::Resources).to receive(:add_resource_dsl).with(:test_resource)
+ end
+
+ it "defaults to false" do
+ expect(klass.preview_resource).to eq false
+ end
+
+ it "can be set to true" do
+ klass.preview_resource(true)
+ expect(klass.preview_resource).to eq true
+ end
+
+ it "does not affect provides by default" do
+ expect(Chef.resource_handler_map).to receive(:set).with(:test_resource, klass, { canonical: true })
+ klass.resource_name(:test_resource)
+ end
+
+ it "adds allow_cookbook_override when true" do
+ expect(Chef.resource_handler_map).to receive(:set).with(:test_resource, klass, { canonical: true, allow_cookbook_override: true })
+ klass.preview_resource(true)
+ klass.resource_name(:test_resource)
+ end
+
+ it "allows manually overriding back to false" do
+ expect(Chef.resource_handler_map).to receive(:set).with(:test_resource, klass, { allow_cookbook_override: false })
+ klass.preview_resource(true)
+ klass.provides(:test_resource, allow_cookbook_override: false)
+ end
+ end
end
diff --git a/spec/unit/role_spec.rb b/spec/unit/role_spec.rb
index 1bbbc4c7b0..57f1d5c6ba 100644
--- a/spec/unit/role_spec.rb
+++ b/spec/unit/role_spec.rb
@@ -104,12 +104,12 @@ describe Chef::Role do
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" })
+ expect(@role.default_attributes({ one: "two" })).to eq({ one: "two" })
end
it "should let you return the default attributes hash" do
- @role.default_attributes({ :one => "two" })
- expect(@role.default_attributes).to eq({ :one => "two" })
+ @role.default_attributes({ one: "two" })
+ expect(@role.default_attributes).to eq({ one: "two" })
end
it "should throw an ArgumentError if we aren't a kind of hash" do
@@ -119,12 +119,12 @@ describe Chef::Role do
describe "override_attributes" do
it "should let you set the override attributes hash explicitly" do
- expect(@role.override_attributes({ :one => "two" })).to eq({ :one => "two" })
+ expect(@role.override_attributes({ one: "two" })).to eq({ one: "two" })
end
it "should let you return the override attributes hash" do
- @role.override_attributes({ :one => "two" })
- expect(@role.override_attributes).to eq({ :one => "two" })
+ @role.override_attributes({ one: "two" })
+ expect(@role.override_attributes).to eq({ one: "two" })
end
it "should throw an ArgumentError if we aren't a kind of hash" do
@@ -137,15 +137,15 @@ describe Chef::Role do
@role.name("mars_volta")
@role.description("Great band!")
@role.run_list("one", "two", "role[a]")
- @role.default_attributes({ :el_groupo => "nuevo" })
- @role.override_attributes({ :deloused => "in the comatorium" })
+ @role.default_attributes({ el_groupo: "nuevo" })
+ @role.override_attributes({ deloused: "in the comatorium" })
@example = Chef::Role.new
@example.name("newname")
@example.description("Really Great band!")
@example.run_list("alpha", "bravo", "role[alpha]")
- @example.default_attributes({ :el_groupo => "nuevo dos" })
- @example.override_attributes({ :deloused => "in the comatorium XOXO" })
+ @example.default_attributes({ el_groupo: "nuevo dos" })
+ @example.override_attributes({ deloused: "in the comatorium XOXO" })
end
it "should update all fields except for name" do
@@ -158,13 +158,13 @@ describe Chef::Role do
end
end
- describe "when serialized as JSON", :json => true do
+ describe "when serialized as JSON", json: true do
before(:each) do
@role.name("mars_volta")
@role.description("Great band!")
@role.run_list("one", "two", "role[a]")
- @role.default_attributes({ :el_groupo => "nuevo" })
- @role.override_attributes({ :deloused => "in the comatorium" })
+ @role.default_attributes({ el_groupo: "nuevo" })
+ @role.override_attributes({ deloused: "in the comatorium" })
@serialized_role = Chef::JSONCompat.to_json(@role)
end
@@ -189,20 +189,20 @@ describe Chef::Role do
end
it "should include 'run_list'" do
- #Activesupport messes with Chef json formatting
- #This test should pass with and without activesupport
+ # Activesupport messes with Chef json formatting
+ # This test should pass with and without activesupport
expect(@serialized_role).to match(/"run_list":\["recipe\[one\]","recipe\[two\]","role\[a\]"\]/)
end
describe "and it has per-environment run lists" do
before do
@role.env_run_lists("_default" => ["one", "two", "role[a]"], "production" => ["role[monitoring]", "role[auditing]", "role[apache]"], "dev" => ["role[nginx]"])
- @serialized_role = Chef::JSONCompat.parse(Chef::JSONCompat.to_json(@role), :create_additions => false)
+ @serialized_role = Chef::JSONCompat.parse(Chef::JSONCompat.to_json(@role), create_additions: false)
end
it "includes the per-environment run lists" do
- #Activesupport messes with Chef json formatting
- #This test should pass with and without activesupport
+ # Activesupport messes with Chef json formatting
+ # This test should pass with and without activesupport
expect(@serialized_role["env_run_lists"]["production"]).to eq(["role[monitoring]", "role[auditing]", "role[apache]"])
expect(@serialized_role["env_run_lists"]["dev"]).to eq(["role[nginx]"])
end
@@ -218,7 +218,7 @@ describe Chef::Role do
end
end
- describe "when created from JSON", :json => true do
+ describe "when created from JSON", json: true do
before(:each) do
@role.name("mars_volta")
@role.description("Great band!")
@@ -245,9 +245,9 @@ describe Chef::Role do
end
end
- ROLE_DSL = <<-EOR
-name "ceiling_cat"
-description "like Aliens, but furry"
+ ROLE_DSL = <<~EOR.freeze
+ name "ceiling_cat"
+ description "like Aliens, but furry"
EOR
describe "when loading from disk" do
diff --git a/spec/unit/run_context_spec.rb b/spec/unit/run_context_spec.rb
index f1c3072b8e..bfef3f8836 100644
--- a/spec/unit/run_context_spec.rb
+++ b/spec/unit/run_context_spec.rb
@@ -184,7 +184,7 @@ describe Chef::RunContext do
describe "handling reboot requests" do
let(:expected) do
- { :reason => "spec tests require a reboot" }
+ { reason: "spec tests require a reboot" }
end
it "stores and deletes the reboot request" do
diff --git a/spec/unit/run_list/run_list_item_spec.rb b/spec/unit/run_list/run_list_item_spec.rb
index 3f8fd2ab3b..b57a7dcd53 100644
--- a/spec/unit/run_list/run_list_item_spec.rb
+++ b/spec/unit/run_list/run_list_item_spec.rb
@@ -22,15 +22,15 @@ 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")
+ item = Chef::RunList::RunListItem.new(type: "fuuu", name: "uuuu")
expect(item.to_s).to eq("fuuu[uuuu]")
end
diff --git a/spec/unit/run_list/versioned_recipe_list_spec.rb b/spec/unit/run_list/versioned_recipe_list_spec.rb
index 859fee75ec..e116ffc130 100644
--- a/spec/unit/run_list/versioned_recipe_list_spec.rb
+++ b/spec/unit/run_list/versioned_recipe_list_spec.rb
@@ -54,25 +54,25 @@ 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(%w{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(%w{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
@@ -85,9 +85,9 @@ describe Chef::RunList::VersionedRecipeList 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
@@ -106,9 +106,9 @@ describe Chef::RunList::VersionedRecipeList 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
@@ -151,7 +151,7 @@ describe Chef::RunList::VersionedRecipeList do
let(:versioned_recipes) do
[
- { :name => "apt", :version => "~> 1.2.0" },
+ { name: "apt", version: "~> 1.2.0" },
]
end
@@ -170,7 +170,7 @@ describe Chef::RunList::VersionedRecipeList do
let(:versioned_recipes) do
[
- { :name => "apt::cacher", :version => "~> 1.2.0" },
+ { name: "apt::cacher", version: "~> 1.2.0" },
]
end
diff --git a/spec/unit/run_list_spec.rb b/spec/unit/run_list_spec.rb
index 0dcd349ced..ac062c665d 100644
--- a/spec/unit/run_list_spec.rb
+++ b/spec/unit/run_list_spec.rb
@@ -170,12 +170,12 @@ describe Chef::RunList do
@role = Chef::Role.new
@role.name "stubby"
@role.run_list "one", "two"
- @role.default_attributes :one => :two
- @role.override_attributes :three => :four
+ @role.default_attributes one: :two
+ @role.override_attributes three: :four
@role.env_run_list["production"] = Chef::RunList.new( "one", "two", "five")
allow(Chef::Role).to receive(:load).and_return(@role)
- @rest = double("Chef::ServerAPI", { :get => @role.to_hash, :url => "/" })
+ @rest = double("Chef::ServerAPI", { get: @role.to_hash, url: "/" })
allow(Chef::ServerAPI).to receive(:new).and_return(@rest)
@run_list << "role[stubby]"
@@ -197,7 +197,7 @@ describe Chef::RunList do
describe "from the chef server" do
it "should load the role from the chef server" do
- #@rest.should_receive(:get).with("roles/stubby")
+ # @rest.should_receive(:get).with("roles/stubby")
expansion = @run_list.expand("_default", "server")
expect(expansion.recipes).to eq(%w{one two kitty})
end
@@ -263,7 +263,7 @@ describe Chef::RunList do
it "should recurse into a child role" do
dog = Chef::Role.new
dog.name "dog"
- dog.default_attributes :seven => :nine
+ dog.default_attributes seven: :nine
dog.run_list "three"
@role.run_list << "role[dog]"
allow(Chef::Role).to receive(:from_disk).with("stubby").and_return(@role)
@@ -277,7 +277,7 @@ describe Chef::RunList do
it "should not recurse infinitely" do
dog = Chef::Role.new
dog.name "dog"
- dog.default_attributes :seven => :nine
+ dog.default_attributes seven: :nine
dog.run_list "role[dog]", "three"
@role.run_list << "role[dog]"
allow(Chef::Role).to receive(:from_disk).with("stubby").and_return(@role)
diff --git a/spec/unit/runner_spec.rb b/spec/unit/runner_spec.rb
index db52862a9c..1effe3157c 100644
--- a/spec/unit/runner_spec.rb
+++ b/spec/unit/runner_spec.rb
@@ -258,10 +258,10 @@ describe Chef::Runner do
end
expect(exception).to be_a(Chef::Exceptions::MultipleFailures)
- 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
+ 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
E
expect(exception.message).to eq(expected_message)
diff --git a/spec/unit/scan_access_control_spec.rb b/spec/unit/scan_access_control_spec.rb
index c747f6cc4a..ec3c088b48 100644
--- a/spec/unit/scan_access_control_spec.rb
+++ b/spec/unit/scan_access_control_spec.rb
@@ -49,7 +49,7 @@ describe Chef::ScanAccessControl do
describe "when the fs entity exists" do
before do
- @stat = double("File::Stat for #{@new_resource.path}", :uid => 0, :gid => 0, :mode => 00100644)
+ @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)
expect(File).to receive(:stat).with(@real_file).and_return(@stat)
expect(File).to receive(:exist?).with(@new_resource.path).and_return(true)
@@ -128,7 +128,7 @@ describe Chef::ScanAccessControl do
end
it "sets the owner of current_resource to the username of the current owner" do
- @root_passwd = double("Struct::Passwd for uid 0", :name => "root")
+ @root_passwd = double("Struct::Passwd for uid 0", name: "root")
expect(Etc).to receive(:getpwuid).with(0).and_return(@root_passwd)
@scanner.set_all!
@@ -163,7 +163,7 @@ describe Chef::ScanAccessControl do
end
it "sets the group of the current resource to the group name" do
- @group_entry = double("Struct::Group for wheel", :name => "wheel")
+ @group_entry = double("Struct::Group for wheel", name: "wheel")
expect(Etc).to receive(:getgrgid).with(0).and_return(@group_entry)
@scanner.set_all!
diff --git a/spec/unit/shell/model_wrapper_spec.rb b/spec/unit/shell/model_wrapper_spec.rb
index 00425f2a01..bcce7c1a08 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
@@ -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...
diff --git a/spec/unit/shell/shell_ext_spec.rb b/spec/unit/shell/shell_ext_spec.rb
index 0afa1f6390..7ddacf8476 100644
--- a/spec/unit/shell/shell_ext_spec.rb
+++ b/spec/unit/shell/shell_ext_spec.rb
@@ -34,8 +34,8 @@ describe Shell::Extensions do
it "finds a subsession in irb for an object" do
target_context_obj = Chef::Node.new
- irb_context = double("context", :main => target_context_obj)
- irb_session = double("irb session", :context => irb_context)
+ irb_context = double("context", main: target_context_obj)
+ irb_session = double("irb session", context: irb_context)
@job_manager.jobs = [[:thread, irb_session]]
allow(@root_context).to receive(:jobs).and_return(@job_manager)
@root_context.ensure_session_select_defined
@@ -92,9 +92,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)
diff --git a/spec/unit/shell/shell_session_spec.rb b/spec/unit/shell/shell_session_spec.rb
index 7ed372f375..ce66676196 100644
--- a/spec/unit/shell/shell_session_spec.rb
+++ b/spec/unit/shell/shell_session_spec.rb
@@ -53,16 +53,16 @@ describe Shell::ClientSession do
let(:session) { Shell::ClientSession.instance }
let(:client) do
double("Chef::Client.new",
- :run_ohai => true,
- :load_node => true,
- :build_node => true,
- :register => true,
- :sync_cookbooks => {}
+ run_ohai: true,
+ load_node: true,
+ build_node: true,
+ register: true,
+ sync_cookbooks: {}
)
end
before do
- Chef::Config[:shell_config] = { :override_runlist => [Chef::RunList::RunListItem.new("shell::override")] }
+ Chef::Config[:shell_config] = { override_runlist: [Chef::RunList::RunListItem.new("shell::override")] }
session.node = node
session.json_configuration = json_attribs
end
@@ -90,16 +90,16 @@ describe Shell::SoloSession do
let(:session) { Shell::SoloSession.instance }
let(:client) do
double("Chef::Client.new",
- :run_ohai => true,
- :load_node => true,
- :build_node => true,
- :register => true,
- :sync_cookbooks => {}
+ run_ohai: true,
+ load_node: true,
+ build_node: true,
+ register: true,
+ sync_cookbooks: {}
)
end
before do
- Chef::Config[:shell_config] = { :override_runlist => [Chef::RunList::RunListItem.new("shell::override")] }
+ Chef::Config[:shell_config] = { override_runlist: [Chef::RunList::RunListItem.new("shell::override")] }
session.node = node
session.json_configuration = json_attribs
end
@@ -128,18 +128,18 @@ describe Shell::StandAloneSession do
let(:session) { Shell::StandAloneSession.instance }
let(:client) do
double("Chef::Client.new",
- :run_ohai => true,
- :load_node => true,
- :build_node => true,
- :register => true,
- :sync_cookbooks => {}
+ run_ohai: true,
+ load_node: true,
+ build_node: true,
+ register: true,
+ sync_cookbooks: {}
)
end
let(:recipe) { Chef::Recipe.new(nil, nil, run_context) }
let(:run_context) { Chef::RunContext.new(node, {}, events) }
before do
- Chef::Config[:shell_config] = { :override_runlist => [Chef::RunList::RunListItem.new("shell::override")] }
+ Chef::Config[:shell_config] = { override_runlist: [Chef::RunList::RunListItem.new("shell::override")] }
session.node = node
session.json_configuration = json_attribs
session.run_context = run_context
@@ -166,7 +166,7 @@ describe Shell::StandAloneSession do
it "runs chef with the standalone recipe" do
allow(session).to receive(:node_built?).and_return(true)
allow(Chef::Log).to receive(:level)
- chef_runner = double("Chef::Runner.new", :converge => :converged)
+ chef_runner = double("Chef::Runner.new", converge: :converged)
# pre-heat resource collection cache
session.resource_collection
@@ -185,7 +185,7 @@ describe Shell::SoloLegacySession do
let(:json_attribs) { { "a" => "b" } }
before do
- Chef::Config[:shell_config] = { :override_runlist => [Chef::RunList::RunListItem.new("shell::override")] }
+ Chef::Config[:shell_config] = { override_runlist: [Chef::RunList::RunListItem.new("shell::override")] }
Chef::Config[:shell_solo] = true
@session = Shell::SoloLegacySession.instance
@node = Chef::Node.new
@@ -214,7 +214,7 @@ describe Shell::SoloLegacySession do
it "keeps json attribs and passes them to the node for consumption" do
@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"
+ # pending "1) keep attribs in an ivar 2) pass them to the node 3) feed them to the node on reset"
end
it "generates its resource collection from the compiled cookbooks and the ad hoc recipe" do
@@ -223,14 +223,13 @@ describe Shell::SoloLegacySession do
@run_context.resource_collection << kitteh_cat
keyboard_cat = Chef::Resource::Cat.new("keyboard_cat")
@recipe.run_context.resource_collection << keyboard_cat
- #@session.rebuild_collection
+ # @session.rebuild_collection
expect(@session.resource_collection).to include(kitteh_cat, keyboard_cat)
end
it "runs chef with a resource collection from the compiled cookbooks" do
allow(@session).to receive(:node_built?).and_return(true)
- allow(Chef::Log).to receive(:level)
- chef_runner = double("Chef::Runner.new", :converge => :converged)
+ chef_runner = double("Chef::Runner.new", converge: :converged)
expect(Chef::Runner).to receive(:new).with(an_instance_of(Chef::RunContext)).and_return(chef_runner)
expect(@recipe.run_chef).to eq(:converged)
@@ -238,11 +237,11 @@ describe Shell::SoloLegacySession do
it "passes the shell CLI args to the client" do
@client = double("Chef::Client.new",
- :run_ohai => true,
- :load_node => true,
- :build_node => true,
- :register => true,
- :sync_cookbooks => {})
+ run_ohai: true,
+ load_node: true,
+ build_node: true,
+ register: true,
+ sync_cookbooks: {})
expect(Chef::Client).to receive(:new).with(json_attribs, Chef::Config[:shell_config]).and_return(@client)
@session.json_configuration = json_attribs
@session.send(:rebuild_node)
diff --git a/spec/unit/user_spec.rb b/spec/unit/user_spec.rb
index a1806db987..48dbf010e9 100644
--- a/spec/unit/user_spec.rb
+++ b/spec/unit/user_spec.rb
@@ -17,7 +17,7 @@
#
# DEPRECATION NOTE
-# This code only remains to support users still operating with
+# This code only remains to support users still operating with
# Open Source Chef Server 11 and should be removed once support
# for OSC 11 ends. New development should occur in user_spec.rb.
@@ -243,7 +243,7 @@ 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
@@ -260,7 +260,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 16f0d0158b..074a68840e 100644
--- a/spec/unit/user_v1_spec.rb
+++ b/spec/unit/user_v1_spec.rb
@@ -311,7 +311,7 @@ describe Chef::UserV1 do
end
describe "Versioned API Interactions" do
- let(:response_406) { OpenStruct.new(:code => "406") }
+ let(:response_406) { OpenStruct.new(code: "406") }
let(:exception_406) { Net::HTTPServerException.new("406 Not Acceptable", response_406) }
before (:each) do
@@ -334,13 +334,13 @@ describe Chef::UserV1 do
let(:payload) do
{
- :username => "some_username",
- :display_name => "some_display_name",
- :first_name => "some_first_name",
- :middle_name => "some_middle_name",
- :last_name => "some_last_name",
- :email => "some_email",
- :password => "some_password",
+ username: "some_username",
+ display_name: "some_display_name",
+ first_name: "some_first_name",
+ middle_name: "some_middle_name",
+ last_name: "some_last_name",
+ email: "some_email",
+ password: "some_password",
}
end
@@ -356,14 +356,14 @@ describe Chef::UserV1 do
context "when server API V1 is not valid on the Chef Server receiving the request" do
let(:payload) do
{
- :username => "some_username",
- :display_name => "some_display_name",
- :first_name => "some_first_name",
- :middle_name => "some_middle_name",
- :last_name => "some_last_name",
- :email => "some_email",
- :password => "some_password",
- :public_key => "some_public_key",
+ username: "some_username",
+ display_name: "some_display_name",
+ first_name: "some_first_name",
+ middle_name: "some_middle_name",
+ last_name: "some_last_name",
+ email: "some_email",
+ password: "some_password",
+ public_key: "some_public_key",
}
end
@@ -373,7 +373,7 @@ describe Chef::UserV1 do
end
context "when the server returns a 400" do
- let(:response_400) { OpenStruct.new(:code => "400") }
+ let(:response_400) { OpenStruct.new(code: "400") }
let(:exception_400) { Net::HTTPServerException.new("400 Bad Request", response_400) }
context "when the 400 was due to public / private key fields no longer being supported" do
@@ -444,12 +444,12 @@ describe Chef::UserV1 do
describe "create" do
let(:payload) do
{
- :username => "some_username",
- :display_name => "some_display_name",
- :first_name => "some_first_name",
- :last_name => "some_last_name",
- :email => "some_email",
- :password => "some_password",
+ username: "some_username",
+ display_name: "some_display_name",
+ first_name: "some_first_name",
+ last_name: "some_last_name",
+ email: "some_email",
+ password: "some_password",
}
end
before do
@@ -473,7 +473,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
@@ -496,7 +496,7 @@ 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
diff --git a/spec/unit/util/diff_spec.rb b/spec/unit/util/diff_spec.rb
index 4bb0abd087..70376bcdb1 100644
--- a/spec/unit/util/diff_spec.rb
+++ b/spec/unit/util/diff_spec.rb
@@ -546,7 +546,7 @@ shared_examples_for "a diff util" do
end
-describe Chef::Util::Diff, :uses_diff => true do
+describe Chef::Util::Diff, uses_diff: true do
let!(:old_file) { old_tempfile.path }
let!(:new_file) { new_tempfile.path }
diff --git a/spec/unit/util/dsc/configuration_generator_spec.rb b/spec/unit/util/dsc/configuration_generator_spec.rb
index cfa7a4e264..faf554326d 100644
--- a/spec/unit/util/dsc/configuration_generator_spec.rb
+++ b/spec/unit/util/dsc/configuration_generator_spec.rb
@@ -76,7 +76,7 @@ describe Chef::Util::DSC::ConfigurationGenerator do
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 do
- conf_man.send(:get_merged_configuration_flags!, { :outputpath => "a" }, "hello")
+ conf_man.send(:get_merged_configuration_flags!, { outputpath: "a" }, "hello")
end.to raise_error(ArgumentError)
end
it "should be case insensitive for switches that are not allowed" do
expect do
- conf_man.send(:get_merged_configuration_flags!, { :OutputPath => "a" }, "hello")
+ conf_man.send(:get_merged_configuration_flags!, { OutputPath: "a" }, "hello")
end.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
diff --git a/spec/unit/util/dsc/lcm_output_parser_spec.rb b/spec/unit/util/dsc/lcm_output_parser_spec.rb
index d59497de6f..32e5c0e07f 100644
--- a/spec/unit/util/dsc/lcm_output_parser_spec.rb
+++ b/spec/unit/util/dsc/lcm_output_parser_spec.rb
@@ -19,146 +19,230 @@
require "chef/util/dsc/lcm_output_parser"
describe Chef::Util::DSC::LocalConfigurationManager::Parser do
- context "empty input parameter" do
+ context "empty input parameter for WhatIfParser" 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, false) }.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, false) }.to raise_error(Chef::Exceptions::LCMParser)
end
end
- context "correctly formatted output from lcm" do
+ context "empty input parameter for TestDSCParser" do
+ it "raises an exception when there are no valid lines" do
+ str = <<-EOF
+
+ EOF
+ expect { Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true) }.to raise_error(Chef::Exceptions::LCMParser)
+ end
+
+ it "raises an exception for a nil input" do
+ expect { Chef::Util::DSC::LocalConfigurationManager::Parser.parse(nil, true) }.to raise_error(Chef::Exceptions::LCMParser)
+ end
+ end
+
+ context "correctly formatted output from lcm for WhatIfParser" do
it "returns a single resource when only 1 logged with the correct name" do
- str = <<EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources.length).to eq(1)
expect(resources[0].name).to eq("[name]")
end
it "identifies when a resource changes the state of the system" do
- str = <<EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Start Set ] [name]
-logtype: [machinename]: LCM: [ End Set ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Start Set ] [name]
+ logtype: [machinename]: LCM: [ End Set ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].changes_state?).to be_truthy
end
it "preserves the log provided for how the system changed the state" do
- str = <<EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Start Set ] [name]
-logtype: [machinename]: [message]
-logtype: [machinename]: LCM: [ End Set ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Start Set ] [name]
+ logtype: [machinename]: [message]
+ logtype: [machinename]: LCM: [ End Set ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].change_log).to match_array(["[name]", "[message]", "[name]"])
end
- it "should return false for changes_state?" do
- str = <<EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Skip Set ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ it "returns false for changes_state?" do
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Skip Set ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].changes_state?).to be_falsey
end
- it "should return an empty array for change_log if changes_state? is false" do
- str = <<EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Skip Set ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ it "returns an empty array for change_log if changes_state? is false" do
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Skip Set ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].change_log).to be_empty
end
end
- context "Incorrectly formatted output from LCM" do
- it "should allow missing a [End Resource] when its the last one and still find all the resource" do
- str = <<-EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Skip Set ]
-logtype: [machinename]: LCM: [ End Resource ]
-logtype: [machinename]: LCM: [ Start Resource ] [name2]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ End Set ]
-logtype: [machinename]: LCM: [ End Set ]
+ context "correctly formatted output from lcm for TestDSCParser" do
+ it "returns a single resource when only 1 logged with the correct name" do
+ str = <<~EOF
+ InDesiredState : False
+ ResourcesInDesiredState :
+ ResourcesNotInDesiredState: [name]
+ ReturnValue : 0
+ PSComputerName : .
+EOF
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true)
+ expect(resources.length).to eq(1)
+ expect(resources[0].name).to eq("[name]")
+ end
+
+ it "identifies when a resource changes the state of the system" do
+ str = <<~EOF
+ InDesiredState : False
+ ResourcesInDesiredState :
+ ResourcesNotInDesiredState: [name]
+ ReturnValue : 0
+ PSComputerName : .
EOF
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true)
+ expect(resources[0].changes_state?).to be_truthy
+ end
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ it "returns false for changes_state?" do
+ str = <<~EOF
+ InDesiredState : True
+ ResourcesInDesiredState : [name]
+ ResourcesNotInDesiredState:
+ ReturnValue : 0
+ PSComputerName : .
+EOF
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true)
+ expect(resources[0].changes_state?).to be_falsey
+ end
+
+ it "returns an empty array for change_log if changes_state? is false" do
+ str = <<~EOF
+ InDesiredState : True
+ ResourcesInDesiredState : [name]
+ ResourcesNotInDesiredState:
+ ReturnValue : 0
+ PSComputerName : .
+EOF
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true)
+ expect(resources[0].change_log).to be_empty
+ end
+ end
+
+ context "Incorrectly formatted output from LCM for WhatIfParser" do
+ it "allows missing [End Resource] when its the last one and still find all the resource" do
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Skip Set ]
+ logtype: [machinename]: LCM: [ End Resource ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name2]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ End Set ]
+ logtype: [machinename]: LCM: [ End Set ]
+EOF
+
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].changes_state?).to be_falsey
expect(resources[1].changes_state?).to be_truthy
end
- it "should allow missing a [End Resource] when its the first one and still find all the resource" do
- str = <<-EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Skip Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name2]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ End Set ]
-logtype: [machinename]: LCM: [ End Resource ]
-logtype: [machinename]: LCM: [ End Set ]
+ it "allow missing [End Resource] when its the first one and still find all the resource" do
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Skip Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name2]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ End Set ]
+ logtype: [machinename]: LCM: [ End Resource ]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].changes_state?).to be_falsey
expect(resources[1].changes_state?).to be_truthy
end
- it "should allow missing set and end resource and assume an unconverged resource in this case" do
- str = <<-EOF
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Start Resource ] [name2]
-logtype: [machinename]: LCM: [ Start Test ]
-logtype: [machinename]: LCM: [ End Test ]
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ End Set ]
-logtype: [machinename]: LCM: [ End Resource ]
-logtype: [machinename]: LCM: [ End Set ]
+ it "allows missing set and end resource and assume an unconverged resource in this case" do
+ str = <<~EOF
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name2]
+ logtype: [machinename]: LCM: [ Start Test ]
+ logtype: [machinename]: LCM: [ End Test ]
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ End Set ]
+ logtype: [machinename]: LCM: [ End Resource ]
+ logtype: [machinename]: LCM: [ End Set ]
EOF
- resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str)
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, false)
expect(resources[0].changes_state?).to be_truthy
expect(resources[0].name).to eql("[name]")
expect(resources[1].changes_state?).to be_truthy
expect(resources[1].name).to eql("[name2]")
end
end
+
+ context "Incorrectly formatted output from LCM for TestDSCParser" do
+ it "allows missing [End Resource] when its the last one and still find all the resource" do
+ str = <<~EOF
+ InDesiredState : True
+ ResourcesInDesiredState :
+ ResourcesNotInDesiredState: [name]
+ ReturnValue : 0
+ PSComputerName : .
+ InDesiredState : True
+ ResourcesInDesiredState :
+ ResourcesNotInDesiredState: [name2]
+ ReturnValue : 0
+ PSComputerName : .
+EOF
+
+ resources = Chef::Util::DSC::LocalConfigurationManager::Parser.parse(str, true)
+ expect(resources[0].changes_state?).to be_falsey
+ end
+ end
end
diff --git a/spec/unit/util/dsc/local_configuration_manager_spec.rb b/spec/unit/util/dsc/local_configuration_manager_spec.rb
index 3f1210dbf1..cce5a39537 100644
--- a/spec/unit/util/dsc/local_configuration_manager_spec.rb
+++ b/spec/unit/util/dsc/local_configuration_manager_spec.rb
@@ -24,46 +24,47 @@ describe Chef::Util::DSC::LocalConfigurationManager do
let(:lcm) { Chef::Util::DSC::LocalConfigurationManager.new(nil, "tmp") }
let(:normal_lcm_output) do
- <<-EOH
-logtype: [machinename]: LCM: [ Start Set ]
-logtype: [machinename]: LCM: [ Start Resource ] [name]
-logtype: [machinename]: LCM: [ End Resource ] [name]
-logtype: [machinename]: LCM: [ End Set ]
+ <<~EOH
+ logtype: [machinename]: LCM: [ Start Set ]
+ logtype: [machinename]: LCM: [ Start Resource ] [name]
+ logtype: [machinename]: LCM: [ End Resource ] [name]
+ logtype: [machinename]: LCM: [ End Set ]
EOH
end
let(:no_whatif_lcm_output) do
- <<-EOH
-Start-DscConfiguration : A parameter cannot be found\r\n that matches parameter name 'whatif'.
-At line:1 char:123
-+ run-somecommand -whatif
-+ ~~~~~~~~
- + CategoryInfo : InvalidArgument: (:) [Start-DscConfiguration], ParameterBindingException
- + FullyQualifiedErrorId : NamedParameterNotFound,SomeCompany.SomeAssembly.Commands.RunSomeCommand
+ <<~EOH
+ Start-DscConfiguration : A parameter cannot be found\r\n that matches parameter name 'whatif'.
+ At line:1 char:123
+ + run-somecommand -whatif
+ + ~~~~~~~~
+ + CategoryInfo : InvalidArgument: (:) [Start-DscConfiguration], ParameterBindingException
+ + FullyQualifiedErrorId : NamedParameterNotFound,SomeCompany.SomeAssembly.Commands.RunSomeCommand
EOH
end
let(:dsc_resource_import_failure_output) do
- <<-EOH
-PowerShell provider MSFT_xWebsite failed to execute Test-TargetResource functionality with error message: Please ensure that WebAdministration module is installed. + CategoryInfo : InvalidOperation: (:) [], CimException + FullyQualifiedErrorId : ProviderOperationExecutionFailure + PSComputerName : . PowerShell provider MSFT_xWebsite failed to execute Test-TargetResource functionality with error message: Please ensure that WebAdministration module is installed. + CategoryInfo : InvalidOperation: (:) [], CimException + FullyQualifiedErrorId : ProviderOperationExecutionFailure + PSComputerName : . The SendConfigurationApply function did not succeed. + CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException + FullyQualifiedErrorId : MI RESULT 1 + PSComputerName : .
+ <<~EOH
+ PowerShell provider MSFT_xWebsite failed to execute Test-TargetResource functionality with error message: Please ensure that WebAdministration module is installed. + CategoryInfo : InvalidOperation: (:) [], CimException + FullyQualifiedErrorId : ProviderOperationExecutionFailure + PSComputerName : . PowerShell provider MSFT_xWebsite failed to execute Test-TargetResource functionality with error message: Please ensure that WebAdministration module is installed. + CategoryInfo : InvalidOperation: (:) [], CimException + FullyQualifiedErrorId : ProviderOperationExecutionFailure + PSComputerName : . The SendConfigurationApply function did not succeed. + CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException + FullyQualifiedErrorId : MI RESULT 1 + PSComputerName : .
EOH
end
let(:lcm_status) do
- double("LCM cmdlet status", :stderr => lcm_standard_error, :return_value => lcm_standard_output, :succeeded? => lcm_cmdlet_success)
+ double("LCM cmdlet status", stderr: lcm_standard_error, return_value: lcm_standard_output, succeeded?: lcm_cmdlet_success)
end
describe "test_configuration method invocation" do
context "when interacting with the LCM using a PowerShell cmdlet" do
before(:each) do
allow(lcm).to receive(:run_configuration_cmdlet).and_return(lcm_status)
+ allow(lcm).to receive(:ps_version_gte_5?).and_return(false)
end
context "that returns successfully" do
let(:lcm_standard_output) { normal_lcm_output }
let(:lcm_standard_error) { nil }
let(:lcm_cmdlet_success) { true }
- it "should successfully return resource information for normally formatted output when cmdlet the cmdlet succeeds" do
+ it "successfully returns resource information for normally formatted output when cmdlet the cmdlet succeeds" do
test_configuration_result = lcm.test_configuration("config", {})
expect(test_configuration_result.class).to be(Array)
expect(test_configuration_result.length).to be > 0
@@ -71,6 +72,58 @@ EOH
end
end
+ context "when running on PowerShell version 5" do
+ let(:lcm_standard_output) { normal_lcm_output }
+ let(:lcm_standard_error) { nil }
+ let(:lcm_cmdlet_success) { true }
+
+ it "successfully returns resource information for normally formatted output when cmdlet the cmdlet succeeds" do
+ allow(lcm).to receive(:ps_version_gte_5?).and_return(true)
+ test_configuration_result = lcm.test_configuration("config", {})
+ expect(test_configuration_result.class).to be(Array)
+ expect(test_configuration_result.length).to be > 0
+ expect(Chef::Log).not_to receive(:warn)
+ end
+ end
+
+ context "when running on PowerShell version less than 5" do
+ let(:lcm_standard_output) { normal_lcm_output }
+ let(:lcm_standard_error) { nil }
+ let(:lcm_cmdlet_success) { true }
+
+ it "successfully returns resource information for normally formatted output when cmdlet the cmdlet succeeds" do
+ allow(lcm).to receive(:ps_version_gte_5?).and_return(false)
+ test_configuration_result = lcm.test_configuration("config", {})
+ expect(test_configuration_result.class).to be(Array)
+ expect(test_configuration_result.length).to be > 0
+ expect(Chef::Log).not_to receive(:warn)
+ end
+ end
+
+ context "#lcm_command" do
+ let(:common_command_prefix) { "$ProgressPreference = 'SilentlyContinue';" }
+ let(:ps4_base_command) { "#{common_command_prefix} Start-DscConfiguration -path tmp -wait -erroraction 'stop' -force" }
+ let(:lcm_command_ps4) { ps4_base_command + " -whatif; if (! $?) { exit 1 }" }
+ let(:lcm_command_ps5) { "#{common_command_prefix} Test-DscConfiguration -path tmp | format-list" }
+ let(:lcm_standard_output) { normal_lcm_output }
+ let(:lcm_standard_error) { nil }
+ let(:lcm_cmdlet_success) { true }
+
+ it "successfully returns command when apply_configuration true" do
+ expect(lcm.send(:lcm_command, true)).to eq(ps4_base_command)
+ end
+
+ it "successfully returns command when PowerShell version 4" do
+ allow(lcm).to receive(:ps_version_gte_5?).and_return(false)
+ expect(lcm.send(:lcm_command, false)).to eq(lcm_command_ps4)
+ end
+
+ it "successfully returns command when PowerShell version 5" do
+ allow(lcm).to receive(:ps_version_gte_5?).and_return(true)
+ expect(lcm.send(:lcm_command, false)).to eq(lcm_command_ps5)
+ end
+ end
+
context "that fails due to missing what-if switch in DSC resource cmdlet implementation" do
let(:lcm_standard_output) { "" }
let(:lcm_standard_error) { no_whatif_lcm_output }
@@ -80,7 +133,7 @@ EOH
expect(lcm.send(:whatif_not_supported?, no_whatif_lcm_output)).to be_truthy
end
- it "should should return a (possibly empty) array of ResourceInfo instances" do
+ it "returns a (possibly empty) array of ResourceInfo instances" do
expect(Chef::Log).to receive(:warn).at_least(:once)
expect(lcm).to receive(:whatif_not_supported?).and_call_original
test_configuration_result = nil
@@ -94,14 +147,14 @@ EOH
let(:lcm_standard_error) { dsc_resource_import_failure_output }
let(:lcm_cmdlet_success) { false }
- it "should log a warning if the message is formatted as expected when a resource import failure occurs" do
+ it "logs a warning if the message is formatted as expected when a resource import failure occurs" do
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
end
- it "should return a (possibly empty) array of ResourceInfo instances" do
+ it "returns 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
@@ -114,7 +167,7 @@ EOH
let(:lcm_standard_error) { "Abort, Retry, Fail?" }
let(:lcm_cmdlet_success) { false }
- it "should log a warning" do
+ it "logs 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
@@ -122,15 +175,15 @@ EOH
end
end
- it "should identify a correctly formatted error message as a resource import failure" do
+ it "identify a correctly formatted error message as a resource import failure" do
expect(lcm.send(:dsc_module_import_failure?, dsc_resource_import_failure_output)).to be(true)
end
- it "should not identify an incorrectly formatted error message as a resource import failure" do
+ it "does not identify an incorrectly formatted error message as a resource import failure" do
expect(lcm.send(:dsc_module_import_failure?, dsc_resource_import_failure_output.gsub("module", "gibberish"))).to be(false)
end
- it "should not identify a message without a CimException reference as a resource import failure" do
+ it "does not identify a message without a CimException reference as a resource import failure" do
expect(lcm.send(:dsc_module_import_failure?, dsc_resource_import_failure_output.gsub("CimException", "ArgumentException"))).to be(false)
end
end
@@ -139,7 +192,7 @@ EOH
context "when invalid dsc script is given" do
it "raises exception" do
configuration_document = "invalid-config"
- shellout_flags = { :cwd => nil, :environment => nil, :timeout => nil }
+ shellout_flags = { cwd: nil, environment: nil, timeout: nil }
expect { lcm.send(:run_configuration_cmdlet, configuration_document, true, shellout_flags) }.to raise_error(Chef::Exceptions::PowershellCmdletException)
end
end
diff --git a/spec/unit/util/file_edit_spec.rb b/spec/unit/util/file_edit_spec.rb
index 1a71d1d856..5c5b04d8a5 100644
--- a/spec/unit/util/file_edit_spec.rb
+++ b/spec/unit/util/file_edit_spec.rb
@@ -22,29 +22,29 @@ require "tempfile"
describe Chef::Util::FileEdit do
let(:starting_content) do
- <<-EOF
-127.0.0.1 localhost
-255.255.255.255 broadcasthost
-::1 localhost
-fe80::1%lo0 localhost
+ <<~EOF
+ 127.0.0.1 localhost
+ 255.255.255.255 broadcasthost
+ ::1 localhost
+ fe80::1%lo0 localhost
EOF
end
let(:localhost_replaced) do
- <<-EOF
-127.0.0.1 replacement
-255.255.255.255 broadcasthost
-::1 replacement
-fe80::1%lo0 replacement
+ <<~EOF
+ 127.0.0.1 replacement
+ 255.255.255.255 broadcasthost
+ ::1 replacement
+ fe80::1%lo0 replacement
EOF
end
let(:localhost_line_replaced) do
- <<-EOF
-replacement line
-255.255.255.255 broadcasthost
-replacement line
-replacement line
+ <<~EOF
+ replacement line
+ 255.255.255.255 broadcasthost
+ replacement line
+ replacement line
EOF
end
@@ -54,41 +54,41 @@ replacement line
end
let(:localhost_line_deleted) do
- <<-EOF
-255.255.255.255 broadcasthost
+ <<~EOF
+ 255.255.255.255 broadcasthost
EOF
end
let(:append_after_all_localhost) do
- <<-EOF
-127.0.0.1 localhost
-new line inserted
-255.255.255.255 broadcasthost
-::1 localhost
-new line inserted
-fe80::1%lo0 localhost
-new line inserted
+ <<~EOF
+ 127.0.0.1 localhost
+ new line inserted
+ 255.255.255.255 broadcasthost
+ ::1 localhost
+ new line inserted
+ fe80::1%lo0 localhost
+ new line inserted
EOF
end
let(:append_after_content) do
- <<-EOF
-127.0.0.1 localhost
-255.255.255.255 broadcasthost
-::1 localhost
-fe80::1%lo0 localhost
-new line inserted
+ <<~EOF
+ 127.0.0.1 localhost
+ 255.255.255.255 broadcasthost
+ ::1 localhost
+ fe80::1%lo0 localhost
+ new line inserted
EOF
end
let(:append_twice) do
- <<-EOF
-127.0.0.1 localhost
-255.255.255.255 broadcasthost
-::1 localhost
-fe80::1%lo0 localhost
-once
-twice
+ <<~EOF
+ 127.0.0.1 localhost
+ 255.255.255.255 broadcasthost
+ ::1 localhost
+ fe80::1%lo0 localhost
+ once
+ twice
EOF
end
diff --git a/spec/unit/util/powershell/cmdlet_spec.rb b/spec/unit/util/powershell/cmdlet_spec.rb
index 800e4cc9c0..144e363979 100644
--- a/spec/unit/util/powershell/cmdlet_spec.rb
+++ b/spec/unit/util/powershell/cmdlet_spec.rb
@@ -75,7 +75,7 @@ describe Chef::Util::Powershell::Cmdlet do
it "does not allow invalid switch names" do
expect do
- @cmdlet.send(:command_switches_string, { :foo! => "bar" })
+ @cmdlet.send(:command_switches_string, { foo!: "bar" })
end.to raise_error(ArgumentError)
end
diff --git a/spec/unit/util/selinux_spec.rb b/spec/unit/util/selinux_spec.rb
index 751092bc9a..0d2d1aeb3f 100644
--- a/spec/unit/util/selinux_spec.rb
+++ b/spec/unit/util/selinux_spec.rb
@@ -1,6 +1,6 @@
#
# Author:: Serdar Sutay (<serdar@chef.io>)
-# Copyright:: Copyright 2013-2017, Chef Software Inc.
+# Copyright:: Copyright 2013-2018, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -60,8 +60,8 @@ 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)
+ 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)
end
it "should report selinux is enabled" do
@@ -73,8 +73,8 @@ 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)
+ 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)
end
it "should report selinux is disabled" do
@@ -86,8 +86,8 @@ 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)
+ 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)
end
it "should throw an error" do
@@ -124,24 +124,21 @@ describe Chef::Util::Selinux do
end
it "should call restorecon non-recursive by default" do
- restorecon_command = "#{@restorecon_enabled_path} -R \"#{path}\""
- expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command)
+ expect(@test_instance).to receive(:shell_out_compacted!).with(@restorecon_enabled_path, "-R", path).twice
@test_instance.restore_security_context(path)
expect(File).not_to receive(:executable?)
@test_instance.restore_security_context(path)
end
it "should call restorecon recursive when recursive is set" do
- restorecon_command = "#{@restorecon_enabled_path} -R -r \"#{path}\""
- expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command)
+ expect(@test_instance).to receive(:shell_out_compacted!).with(@restorecon_enabled_path, "-R", "-r", path).twice
@test_instance.restore_security_context(path, true)
expect(File).not_to receive(:executable?)
@test_instance.restore_security_context(path, true)
end
it "should call restorecon non-recursive when recursive is not set" do
- restorecon_command = "#{@restorecon_enabled_path} -R \"#{path}\""
- expect(@test_instance).to receive(:shell_out!).twice.with(restorecon_command)
+ expect(@test_instance).to receive(:shell_out_compacted!).with(@restorecon_enabled_path, "-R", path).twice
@test_instance.restore_security_context(path)
expect(File).not_to receive(:executable?)
@test_instance.restore_security_context(path)
diff --git a/spec/unit/util/windows/logon_session_spec.rb b/spec/unit/util/windows/logon_session_spec.rb
index b9b6c458b6..8a94802bf6 100644
--- a/spec/unit/util/windows/logon_session_spec.rb
+++ b/spec/unit/util/windows/logon_session_spec.rb
@@ -27,7 +27,8 @@ describe ::Chef::Util::Windows::LogonSession do
stub_const("Chef::ReservedNames::Win32::API::System", Class.new )
end
- let(:session) { ::Chef::Util::Windows::LogonSession.new(session_user, password, session_domain) }
+ let(:session) { ::Chef::Util::Windows::LogonSession.new(session_user, password, session_domain, authentication) }
+ let(:authentication) { :remote }
shared_examples_for "it received syntactically invalid credentials" do
it "does not raisees an exception when it is initialized" do
diff --git a/spec/unit/win32/registry_spec.rb b/spec/unit/win32/registry_spec.rb
index 1523ac1919..574f38d8e2 100644
--- a/spec/unit/win32/registry_spec.rb
+++ b/spec/unit/win32/registry_spec.rb
@@ -21,8 +21,8 @@ require "spec_helper"
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) { { 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" }
@@ -41,7 +41,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
+ # Making the values for registry constants available on unix
Win32::Registry::KEY_SET_VALUE = 0x0002
Win32::Registry::KEY_QUERY_VALUE = 0x0001
Win32::Registry::KEY_WRITE = 0x00020000 | 0x0002 | 0x0004
diff --git a/spec/unit/win32/security_spec.rb b/spec/unit/win32/security_spec.rb
index 1c755061ce..b5e441f2a0 100644
--- a/spec/unit/win32/security_spec.rb
+++ b/spec/unit/win32/security_spec.rb
@@ -59,8 +59,51 @@ describe "Chef::Win32::Security", :windows_only do
expect(Chef::ReservedNames::Win32::Security).to receive(:SetNamedSecurityInfoW).and_return(
Chef::ReservedNames::Win32::API::Error::ERROR_USER_NOT_FOUND
)
- expect { Chef::ReservedNames::Win32::Security.set_named_security_info "/temp_path", :SE_FILE_OBJECT, {} }.to raise_error Chef::Exceptions::Chef::Exceptions::UserIDNotFound
+ expect { Chef::ReservedNames::Win32::Security.set_named_security_info "/temp_path", :SE_FILE_OBJECT, {} }.to raise_error Chef::Exceptions::UserIDNotFound
end
end
end
+
+ describe "self.has_admin_privileges?" do
+ context "when the user doesn't have admin privileges" do
+ it "returns false" do
+ allow(Chef::ReservedNames::Win32::Security).to receive(:open_current_process_token).and_raise("Access is denied.")
+ expect(Chef::ReservedNames::Win32::Security.has_admin_privileges?).to be false
+ end
+ end
+
+ context "when open_current_process_token fails with some other error than `Access is Denied`" do
+ it "raises error" do
+ allow(Chef::ReservedNames::Win32::Security).to receive(:open_current_process_token).and_raise("boom")
+ expect { Chef::ReservedNames::Win32::Security.has_admin_privileges? }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
+
+ context "when the user has admin privileges" do
+ it "returns true" do
+ allow(Chef::ReservedNames::Win32::Security).to receive(:open_current_process_token)
+ token = Chef::ReservedNames::Win32::Security.open_current_process_token
+ allow(token).to receive_message_chain(:handle, :handle)
+ allow(Chef::ReservedNames::Win32::Security).to receive(:get_token_information_elevation_type)
+ allow(Chef::ReservedNames::Win32::Security).to receive(:GetTokenInformation).and_return(true)
+ allow_any_instance_of(FFI::Buffer).to receive(:read_ulong).and_return(1)
+ expect(Chef::ReservedNames::Win32::Security.has_admin_privileges?).to be true
+ end
+ end
+ end
+
+ describe "self.get_token_information_elevation_type" do
+ let(:token_rights) { Chef::ReservedNames::Win32::Security::TOKEN_READ }
+
+ let(:token) do
+ Chef::ReservedNames::Win32::Security.open_process_token(
+ Chef::ReservedNames::Win32::Process.get_current_process,
+ token_rights)
+ end
+
+ it "raises error if GetTokenInformation fails" do
+ allow(Chef::ReservedNames::Win32::Security).to receive(:GetTokenInformation).and_return(false)
+ expect { Chef::ReservedNames::Win32::Security.get_token_information_elevation_type(token) }.to raise_error(Chef::Exceptions::Win32APIError)
+ end
+ end
end
diff --git a/spec/unit/windows_service_spec.rb b/spec/unit/windows_service_spec.rb
index 3555b70f1b..45af0f9d9f 100644
--- a/spec/unit/windows_service_spec.rb
+++ b/spec/unit/windows_service_spec.rb
@@ -32,16 +32,18 @@ describe "Chef::Application::WindowsService", :windows_only do
let(:timeout) { 7200 }
let(:shellout_options) do
{
- :timeout => timeout,
- :logger => Chef::Log,
+ timeout: timeout,
+ logger: Chef::Log,
}
end
before do
+ monologger = instance_double("MonoLogger", :level= => nil, :add => nil, :formatter= => nil, :formatter => nil)
+ allow(MonoLogger).to receive(:new).and_return(monologger)
+
Chef::Config.merge!(config_options)
allow(subject).to receive(:configure_chef)
allow(subject).to receive(:parse_options)
- allow(MonoLogger).to receive(:new)
allow(subject).to receive(:running?).and_return(true, false)
allow(subject).to receive(:state).and_return(4)
subject.service_init
@@ -98,7 +100,7 @@ describe "Chef::Application::WindowsService", :windows_only do
end
end
- context "configueres a watchdog timeout" do
+ context "configures a watchdog timeout" do
let(:timeout) { 10 }
before do