diff --git a/src/bosh_azure_cpi/.rubocop.yml b/src/bosh_azure_cpi/.rubocop.yml index a4a6576f5..ea822cf02 100644 --- a/src/bosh_azure_cpi/.rubocop.yml +++ b/src/bosh_azure_cpi/.rubocop.yml @@ -85,6 +85,11 @@ Lint/UnmodifiedReduceAccumulator: # new in 1.1 Lint/UselessRuby2Keywords: # new in 1.23 Enabled: true +Metrics/BlockLength: + Exclude: + - 'spec/unit/vm_manager/create/shared_stuff.rb' + - '**/*_spec.rb' + RSpec/ExcessiveDocstringSpacing: # new in 2.5 Enabled: true @@ -100,8 +105,21 @@ RSpec/Rails/AvoidSetupHook: # new in 2.4 Security/IoMethods: # new in 1.22 Enabled: true +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: AllowOnlyRestArgument. Style/ArgumentsForwarding: # new in 1.1 Enabled: true + Exclude: + # Note: Excluding the following file since it seems like that file might need backwards-compatibility with earlier versions than Ruby v2.7. + - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' + +# Offense count: 6 +# Cop supports --auto-correct. +Style/BisectedAttrAccessor: + Exclude: + # Note: Excluding the following file for the reasons noted within its comments. + - 'lib/cloud/azure/models/vm_cloud_props.rb' Style/CollectionCompact: # new in 1.2 Enabled: true @@ -118,6 +136,13 @@ Style/HashConversion: # new in 1.10 Style/HashExcept: # new in 1.7 Enabled: true +# Offense count: 1 +# Cop supports --auto-correct. +Style/HashTransformValues: + Exclude: + # Note: Excluding the following file since it seems like that file might need backwards-compatibility with earlier versions than Ruby v2.4. + - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' + Style/IfWithBooleanLiteralBranches: # new in 1.9 Enabled: true @@ -158,4 +183,9 @@ Style/StringChars: # new in 1.12 Enabled: true Style/SwapValues: # new in 1.1 - Enabled: true \ No newline at end of file + Enabled: true + +# Cop supports --auto-correct. +# Configuration parameters: AllowNamedUnderscoreVariables. +Style/TrailingUnderscoreVariable: + Enabled: false # Note: This cop makes code harder to read, IMO. diff --git a/src/bosh_azure_cpi/.rubocop_todo.yml b/src/bosh_azure_cpi/.rubocop_todo.yml index 2d76e0418..1a513116c 100644 --- a/src/bosh_azure_cpi/.rubocop_todo.yml +++ b/src/bosh_azure_cpi/.rubocop_todo.yml @@ -1,6 +1,6 @@ # This configuration was generated by # `rubocop --auto-gen-config` -# on 2021-12-01 01:02:33 UTC using RuboCop version 1.23.0. +# on 2022-01-27 22:28:16 UTC using RuboCop version 1.23.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new @@ -14,205 +14,6 @@ Bundler/OrderedGems: Exclude: - 'Gemfile' -# Offense count: 5 -# Cop supports --auto-correct. -Layout/ClosingParenthesisIndentation: - Exclude: - - 'lib/cloud/azure/cloud.rb' - - 'spec/unit/cloud/create_vm_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EmptyLineBetweenMethodDefs, EmptyLineBetweenClassDefs, EmptyLineBetweenModuleDefs, AllowAdjacentOneLineDefs, NumberOfEmptyLines. -Layout/EmptyLineBetweenDefs: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 11 -# Cop supports --auto-correct. -# Configuration parameters: AllowAliasSyntax, AllowedMethods. -# AllowedMethods: alias_method, public, protected, private -Layout/EmptyLinesAroundAttributeAccessor: - Exclude: - - 'lib/cloud/azure/cloud.rb' - - 'lib/cloud/azure/meta_store/stemcell_meta.rb' - - 'lib/cloud/azure/models/bosh_vm_meta.rb' - - 'lib/cloud/azure/models/config.rb' - - 'lib/cloud/azure/models/ephemeral_disk.rb' - - 'lib/cloud/azure/models/root_disk.rb' - - 'lib/cloud/azure/storage/storage_account_manager.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Exclude: - - 'lib/cloud/azure/cloud.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith, Severity. -# SupportedStylesAlignWith: keyword, variable, start_of_line -Layout/EndAlignment: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: consistent, consistent_relative_to_receiver, special_for_inner_method_call, special_for_inner_method_call_in_parentheses -Layout/FirstArgumentIndentation: - Exclude: - - 'lib/cloud/azure/cloud.rb' - - 'spec/unit/cloud/create_vm_spec.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: special_inside_parentheses, consistent, align_braces -Layout/FirstHashElementIndentation: - Exclude: - - 'spec/unit/azure_client/get_operation_spec.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: normal, indented_internal_methods -Layout/IndentationConsistency: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IndentationWidth, EnforcedStyle. -# SupportedStyles: spaces, tabs -Layout/IndentationStyle: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: Width, IgnoredPatterns. -Layout/IndentationWidth: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: aligned, indented -Layout/LineEndStringConcatenationIndentation: - Exclude: - - 'spec/unit/network_configurator_spec.rb' - -# Offense count: 18 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: aligned, indented, indented_relative_to_receiver -Layout/MultilineMethodCallIndentation: - Exclude: - - 'spec/unit/blob_manager_spec.rb' - - 'spec/unit/cloud/attach_disk_spec.rb' - - 'spec/unit/cloud/create_vm_spec.rb' - - 'spec/unit/helpers_spec.rb' - - 'spec/unit/storage_account_manager_spec.rb' - - 'spec/unit/table_manager_spec.rb' - - 'spec/unit/vm_manager/create/tags_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, EnforcedStyleForExponentOperator. -# SupportedStylesForExponentOperator: space, no_space -Layout/SpaceAroundOperators: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBrackets: space, no_space -Layout/SpaceInsideArrayLiteralBrackets: - Exclude: - - 'spec/unit/vm_manager/create/application_security_group_spec.rb' - - 'spec/unit/vm_manager/create/dynamic_public_ip_spec.rb' - -# Offense count: 30 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space, compact -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideHashLiteralBraces: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'spec/integration/lifecycle_spec.rb' - - 'spec/unit/azure_client/create_public_ip_spec.rb' - - 'spec/unit/cloud/attach_disk_spec.rb' - - 'spec/unit/cloud/shared_stuff.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - - 'spec/unit/vm_manager/create/tags_spec.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: final_newline, final_blank_line -Layout/TrailingEmptyLines: - Exclude: - - 'spec/integration/spec_helper.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: AllowInHeredoc. -Layout/TrailingWhitespace: - Exclude: - - 'lib/cloud/azure/vms/vm_manager_network.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - -# Offense count: 19 -# Configuration parameters: IgnoredMethods. -Lint/AmbiguousBlockAssociation: - Exclude: - - 'spec/unit/azure_client/create_virtual_machine_spec.rb' - - 'spec/unit/azure_client/delete_virtual_machine_spec.rb' - - 'spec/unit/azure_client/restart_virtual_machine_spec.rb' - - 'spec/unit/cloud/set_disk_metadata_spec.rb' - - 'spec/unit/vm_manager/create/vm_is_not_created_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Lint/AmbiguousOperator: - Exclude: - - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -Lint/AmbiguousOperatorPrecedence: - Exclude: - - 'lib/cloud/azure/storage/blob_manager.rb' - - 'lib/cloud/azure/utils/helpers.rb' - - 'spec/unit/blob_manager_spec.rb' - - 'spec/unit/cloud/calculate_vm_cloud_properties_spec.rb' - - 'spec/unit/disk_manager2_spec.rb' - - 'spec/unit/disk_manager_spec.rb' - - 'spec/unit/vhd_utils_spec.rb' - - 'spec/unit/vm_manager/create/availability_set_spec.rb' - -# Offense count: 110 -# Cop supports --auto-correct. -Lint/AmbiguousRegexpLiteral: - Enabled: false - # Offense count: 1 # Configuration parameters: AllowSafeAssignment. Lint/AssignmentInCondition: @@ -247,14 +48,6 @@ Lint/MissingSuper: - 'lib/cloud/azure/cloud.rb' - 'lib/cloud/azure/restapi/azure_client.rb' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowedImplicitNamespaces. -# AllowedImplicitNamespaces: Gem -Lint/RaiseException: - Exclude: - - 'spec/unit/helpers_spec.rb' - # Offense count: 3 Lint/ShadowingOuterLocalVariable: Exclude: @@ -266,27 +59,6 @@ Lint/SuppressedException: Exclude: - 'lib/cloud/azure/utils/helpers.rb' -# Offense count: 91 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: strict, consistent -Lint/SymbolConversion: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/utils/helpers.rb' - - 'spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb' - - 'spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb' - - 'spec/unit/azure_client/get_operation_spec.rb' - - 'spec/unit/azure_client/get_token_spec.rb' - - 'spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb' - - 'spec/unit/helpers_spec.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Lint/ToJSON: - Exclude: - - 'lib/cloud/azure/telemetry/telemetry_event.rb' - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. @@ -304,28 +76,23 @@ Lint/UselessAssignment: - 'lib/cloud/azure/vms/vm_manager.rb' - 'spec/manual_tests/resource_group_name/helpers.rb' -# Offense count: 83 +# Offense count: 87 # Configuration parameters: IgnoredMethods, CountRepeatedAttributes. Metrics/AbcSize: Max: 192 -# Offense count: 769 +# Offense count: 16 # Configuration parameters: CountComments, CountAsOne, ExcludedMethods, IgnoredMethods. # IgnoredMethods: refine Metrics/BlockLength: - Max: 2197 + Max: 69 # Offense count: 7 # Configuration parameters: CountBlocks. Metrics/BlockNesting: Max: 7 -# Offense count: 12 -# Configuration parameters: CountComments, CountAsOne. -Metrics/ClassLength: - Max: 1645 - -# Offense count: 29 +# Offense count: 33 # Configuration parameters: IgnoredMethods. Metrics/CyclomaticComplexity: Max: 39 @@ -338,14 +105,14 @@ Metrics/MethodLength: # Offense count: 1 # Configuration parameters: CountComments, CountAsOne. Metrics/ModuleLength: - Max: 342 + Max: 343 # Offense count: 9 # Configuration parameters: CountKeywordArgs, MaxOptionalParameters. Metrics/ParameterLists: Max: 10 -# Offense count: 30 +# Offense count: 32 # Configuration parameters: IgnoredMethods. Metrics/PerceivedComplexity: Max: 45 @@ -443,26 +210,7 @@ RSpec/BeforeAfterAll: - 'spec/integration/stemcell_spec.rb' - 'spec/unit/blob_manager_spec.rb' -# Offense count: 20 -# Cop supports --auto-correct. -RSpec/ContextMethod: - Exclude: - - 'spec/integration/lifecycle_spec.rb' - - 'spec/integration/stemcell_spec.rb' - - 'spec/unit/logger_spec.rb' - - 'spec/unit/models/vm_cloud_props_spec.rb' - - 'spec/unit/network_spec.rb' - - 'spec/unit/vm_manager/create/accelerated_networking_spec.rb' - - 'spec/unit/vm_manager/create/application_security_group_spec.rb' - - 'spec/unit/vm_manager/create/availability_set_spec.rb' - - 'spec/unit/vm_manager/create/get_root_disk_type_spec.rb' - - 'spec/unit/vm_manager/create/ip_forwarding_spec.rb' - - 'spec/unit/vm_manager/create/managed_identity_spec.rb' - - 'spec/unit/vm_manager/create/network_security_group_spec.rb' - - 'spec/unit/vm_manager/create/stemcell_spec.rb' - - 'spec/unit/vm_manager/create/tags_spec.rb' - -# Offense count: 193 +# Offense count: 177 # Configuration parameters: Prefixes. # Prefixes: when, with, without RSpec/ContextWording: @@ -480,65 +228,25 @@ RSpec/DescribeClass: - 'spec/integration/azure_cpi_spec.rb' - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' -# Offense count: 232 +# Offense count: 249 # Cop supports --auto-correct. # Configuration parameters: SkipBlocks, EnforcedStyle. # SupportedStyles: described_class, explicit RSpec/DescribedClass: Enabled: false -# Offense count: 5 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterExampleGroup: - Exclude: - - 'spec/unit/azure_client/managed_disks_spec.rb' - - 'spec/unit/blob_manager_spec.rb' - - 'spec/unit/cloud/attach_disk_spec.rb' - - 'spec/unit/telemetry/telemetry_manager_spec.rb' - - 'spec/unit/vm_manager/create/use_config_disk_spec.rb' - -# Offense count: 128 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterFinalLet: - Enabled: false - -# Offense count: 23 -# Cop supports --auto-correct. -RSpec/EmptyLineAfterHook: - Exclude: - - 'spec/integration/migrations/availability_zone_migration_spec.rb' - - 'spec/integration/migrations/managed_disks_migration_spec.rb' - - 'spec/integration/network/manual_network_spec.rb' - - 'spec/integration/resources/additional_resource_group_spec.rb' - - 'spec/integration/resources/availability_sets_spec.rb' - - 'spec/integration/resources/availability_zone_spec.rb' - - 'spec/unit/azure_client/create_virtual_machine_spec.rb' - - 'spec/unit/blob_manager_spec.rb' - - 'spec/unit/disk_manager2_spec.rb' - - 'spec/unit/disk_manager_spec.rb' - - 'spec/unit/stemcell_manager_spec.rb' - - 'spec/unit/vm_manager/create/use_config_disk_spec.rb' - -# Offense count: 485 +# Offense count: 489 # Configuration parameters: CountAsOne. RSpec/ExampleLength: Max: 64 -# Offense count: 838 +# Offense count: 867 # Cop supports --auto-correct. # Configuration parameters: CustomTransform, IgnoredWords. RSpec/ExampleWording: Enabled: false -# Offense count: 7 -# Cop supports --auto-correct. -RSpec/ExcessiveDocstringSpacing: - Exclude: - - 'spec/unit/vm_manager/create/application_security_group_spec.rb' - - 'spec/unit/vm_manager/create/dynamic_public_ip_spec.rb' - - 'spec/unit/vm_manager/create/network_security_group_spec.rb' - -# Offense count: 14 +# Offense count: 22 RSpec/ExpectInHook: Exclude: - 'spec/integration/migrations/availability_zone_migration_spec.rb' @@ -550,21 +258,12 @@ RSpec/ExpectInHook: - 'spec/unit/vm_manager/create/application_security_group_spec.rb' - 'spec/unit/vm_manager/create/dynamic_public_ip_spec.rb' -# Offense count: 119 +# Offense count: 122 # Configuration parameters: Include, CustomTransform, IgnoreMethods, SpecSuffixOnly. # Include: **/*_spec*rb*, **/spec/**/* RSpec/FilePath: Enabled: false -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: implicit, each, example -RSpec/HookArgument: - Exclude: - - 'spec/integration/azure_cpi_spec.rb' - - 'spec/integration/spec_helper.rb' - # Offense count: 298 # Configuration parameters: AssignmentOnly. RSpec/InstanceVariable: @@ -587,7 +286,7 @@ RSpec/LeakyConstantDeclaration: - 'spec/unit/models/obj_id_spec.rb' - 'spec/unit/table_manager_spec.rb' -# Offense count: 888 +# Offense count: 898 # Configuration parameters: . # SupportedStyles: have_received, receive RSpec/MessageSpies: @@ -598,11 +297,11 @@ RSpec/MultipleDescribes: Exclude: - 'spec/unit/blob_manager_spec.rb' -# Offense count: 443 +# Offense count: 452 RSpec/MultipleExpectations: Max: 13 -# Offense count: 864 +# Offense count: 908 # Configuration parameters: AllowSubject. RSpec/MultipleMemoizedHelpers: Max: 59 @@ -621,22 +320,10 @@ RSpec/NamedSubject: - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - 'spec/unit/instance_type_mapper_spec.rb' -# Offense count: 619 +# Offense count: 670 RSpec/NestedGroups: Max: 9 -# Offense count: 11 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: not_to, to_not -RSpec/NotToNot: - Exclude: - - 'spec/integration/azure_cpi_spec.rb' - - 'spec/integration/lifecycle_spec.rb' - - 'spec/integration/network/manual_network_spec.rb' - - 'spec/unit/cloud/attach_disk_spec.rb' - - 'spec/unit/cloud/create_vm_spec.rb' - # Offense count: 2 RSpec/OverwritingSetup: Exclude: @@ -651,18 +338,6 @@ RSpec/PredicateMatcher: Exclude: - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' -# Offense count: 22 -# Cop supports --auto-correct. -RSpec/ReceiveCounts: - Exclude: - - 'spec/unit/azure_client/create_storage_account_spec.rb' - - 'spec/unit/disk_manager2_spec.rb' - - 'spec/unit/telemetry/telemetry_manager_spec.rb' - - 'spec/unit/vm_manager/create/application_security_group_spec.rb' - - 'spec/unit/vm_manager/create/availability_set_spec.rb' - - 'spec/unit/vm_manager/create/stemcell_spec.rb' - - 'spec/unit/vm_manager/create/use_config_disk_spec.rb' - # Offense count: 2 RSpec/RepeatedExampleGroupBody: Exclude: @@ -692,12 +367,6 @@ RSpec/StubbedMock: RSpec/VerifiedDoubles: Enabled: false -# Offense count: 1 -# Cop supports --auto-correct. -RSpec/Yield: - Exclude: - - 'spec/unit/telemetry/telemetry_manager_spec.rb' - # Offense count: 42 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. @@ -711,28 +380,6 @@ Style/AccessorGrouping: - 'lib/cloud/azure/network/network.rb' - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: AllowOnlyRestArgument. -Style/ArgumentsForwarding: - Exclude: - - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -Style/BisectedAttrAccessor: - Exclude: - - 'lib/cloud/azure/meta_store/stemcell_meta.rb' - - 'lib/cloud/azure/models/config.rb' - - 'lib/cloud/azure/models/vm_cloud_props.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -Style/CaseLikeIf: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/utils/helpers.rb' - # Offense count: 48 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. @@ -740,54 +387,17 @@ Style/CaseLikeIf: Style/ClassAndModuleChildren: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: IgnoredMethods. -# IgnoredMethods: ==, equal?, eql? -Style/ClassEqualityComparison: - Exclude: - - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: Keywords, RequireColon. -# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW, NOTE -Style/CommentAnnotation: - Exclude: - - 'spec/unit/telemetry/wire_client_spec.rb' - -# Offense count: 61 +# Offense count: 62 # Configuration parameters: AllowedConstants. Style/Documentation: Enabled: false -# Offense count: 2 -# Cop supports --auto-correct. -Style/EmptyLiteral: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/vms/vm_manager_network.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/ExplicitBlockArgument: - Exclude: - - 'spec/spec_helper.rb' - # Offense count: 15 # Configuration parameters: MaxUnannotatedPlaceholdersAllowed, IgnoredMethods. # SupportedStyles: annotated, template, unannotated Style/FormatStringToken: EnforcedStyle: template -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: always, always_true, never -Style/FrozenStringLiteralComment: - Exclude: - - 'spec/unit/utils/bosh_agent_util_spec.rb' - # Offense count: 16 # Cop supports --auto-correct. Style/GlobalStdStream: @@ -802,7 +412,7 @@ Style/GlobalStdStream: - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - 'spec/unit/telemetry/telemetry_manager_spec.rb' -# Offense count: 13 +# Offense count: 12 # Configuration parameters: MinBodyLength. Style/GuardClause: Exclude: @@ -816,48 +426,6 @@ Style/GuardClause: - 'lib/cloud/azure/utils/helpers.rb' - 'spec/manual_tests/resource_group_name/helpers.rb' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowSplatArgument. -Style/HashConversion: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: AllowedReceivers. -Style/HashEachMethods: - Exclude: - - 'lib/cloud/azure/telemetry/telemetry_event.rb' - - 'lib/cloud/azure/telemetry/wire_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. -# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys -Style/HashSyntax: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/HashTransformValues: - Exclude: - - 'spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowIfModifier. -Style/IfInsideElse: - Exclude: - - 'lib/cloud/azure/vms/vm_manager.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/IfUnlessModifier: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - # Offense count: 1 Style/MixinUsage: Exclude: @@ -874,28 +442,6 @@ Style/NegatedIfElseCondition: - 'lib/cloud/azure/telemetry/wire_client.rb' - 'lib/cloud/azure/vms/vm_manager_storage.rb' -# Offense count: 1 -# Cop supports --auto-correct. -Style/NestedTernaryOperator: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IncludeSemanticChanges. -Style/NonNilCheck: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IgnoredMethods. -# SupportedStyles: predicate, comparison -Style/NumericPredicate: - Exclude: - - 'spec/**/*' - - 'lib/cloud/azure/utils/helpers.rb' - # Offense count: 7 Style/OpenStructUse: Exclude: @@ -916,61 +462,6 @@ Style/OptionalBooleanParameter: - 'lib/cloud/azure/storage/blob_manager.rb' - 'lib/cloud/azure/utils/command_runner.rb' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'spec/integration/lifecycle_spec.rb' - -# Offense count: 87 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: same_as_string_literals, single_quotes, double_quotes -Style/QuotedSymbols: - Exclude: - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/utils/bosh_agent_util.rb' - - 'lib/cloud/azure/utils/helpers.rb' - - 'spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb' - - 'spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb' - - 'spec/unit/azure_client/get_operation_spec.rb' - - 'spec/unit/azure_client/get_token_spec.rb' - - 'spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb' - - 'spec/unit/helpers_spec.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -Style/RedundantAssignment: - Exclude: - - 'lib/cloud/azure/disk/config_disk_manager.rb' - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/vms/vm_manager_network.rb' - - 'spec/manual_tests/resource_group_name/helpers.rb' - - 'spec/spec_helper.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -Style/RedundantBegin: - Exclude: - - 'lib/cloud/azure/storage/blob_manager.rb' - - 'lib/cloud/azure/telemetry/telemetry_event_handler.rb' - - 'spec/integration/migrations/managed_disks_migration_spec.rb' - -# Offense count: 40 -# Cop supports --auto-correct. -Style/RedundantFileExtensionInRequire: - Enabled: false - -# Offense count: 13 -# Cop supports --auto-correct. -Style/RedundantRegexpEscape: - Exclude: - - 'spec/integration/azure_cpi_spec.rb' - - 'spec/unit/azure_client/azure_client_spec.rb' - - 'spec/unit/blob_manager_spec.rb' - - 'spec/unit/vm_manager/create/invalid_option_spec.rb' - # Offense count: 2 # Cop supports --auto-correct. # Configuration parameters: AllowMultipleReturnValues. @@ -979,29 +470,6 @@ Style/RedundantReturn: - 'lib/cloud/azure/stemcell/stemcell_manager.rb' - 'lib/cloud/azure/utils/helpers.rb' -# Offense count: 2 -# Cop supports --auto-correct. -Style/SlicingWithRange: - Exclude: - - 'lib/cloud/azure/utils/helpers.rb' - - 'lib/cloud/azure/vms/vm_manager_availability_set.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: AllowModifier. -Style/SoleNestedConditional: - Exclude: - - 'lib/cloud/azure/models/disk_id.rb' - - 'lib/cloud/azure/models/instance_id.rb' - - 'lib/cloud/azure/restapi/azure_client.rb' - - 'lib/cloud/azure/vms/vm_manager_availability_set.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/StringChars: - Exclude: - - 'lib/cloud/azure/vms/vm_manager.rb' - # Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: Mode. @@ -1012,17 +480,6 @@ Style/StringConcatenation: - 'lib/cloud/azure/telemetry/telemetry_manager.rb' - 'spec/unit/telemetry/telemetry_manager_spec.rb' -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Exclude: - - 'lib/cloud/azure/utils/helpers.rb' - - 'spec/unit/cloud/cloud_spec.rb' - - 'spec/unit/utils/bosh_agent_util_spec.rb' - - 'spec/unit/vm_manager/create/tags_spec.rb' - # Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyleForMultiline. @@ -1042,13 +499,6 @@ Style/TrailingCommaInHashLiteral: - 'spec/integration/lifecycle_spec.rb' - 'spec/unit/utils/bosh_agent_util_spec.rb' -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: AllowNamedUnderscoreVariables. -Style/TrailingUnderscoreVariable: - Exclude: - - 'spec/integration/migrations/managed_disks_migration_spec.rb' - # Offense count: 20 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, MinSize, WordRegex. @@ -1066,7 +516,7 @@ Style/WordArray: - 'spec/unit/vm_manager/create/availability_set_spec.rb' - 'spec/unit/vm_manager/delete_spec.rb' -# Offense count: 858 +# Offense count: 921 # Cop supports --auto-correct. # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https diff --git a/src/bosh_azure_cpi/lib/cloud/azure.rb b/src/bosh_azure_cpi/lib/cloud/azure.rb index adbe370eb..cdf4540c1 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure.rb @@ -28,7 +28,7 @@ module AzureCloud; end # Reference: # https://makandracards.com/ninjaconcept/30815-fixing-socketerror-getaddrinfo-name-or-service-not-known-with-ruby-s-resolv-replace-rb # http://www.subelsky.com/2014/05/fixing-socketerror-getaddrinfo-name-or.html -require 'resolv-replace.rb' +require 'resolv-replace' require 'digest/md5' require 'net/http' diff --git a/src/bosh_azure_cpi/lib/cloud/azure/cloud.rb b/src/bosh_azure_cpi/lib/cloud/azure/cloud.rb index e4484119f..2cffff535 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/cloud.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/cloud.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class Cloud < Bosh::Cloud + class Cloud < Bosh::Cloud # rubocop:todo Metrics/ClassLength attr_reader :registry attr_reader :config # Below defines are for test purpose @@ -9,6 +9,7 @@ class Cloud < Bosh::Cloud attr_reader :disk_manager, :disk_manager2, :stemcell_manager, :stemcell_manager2, :light_stemcell_manager attr_reader :props_factory attr_reader :api_version, :stemcell_api_version + include Helpers # CPI API Version @@ -187,11 +188,11 @@ def create_vm(agent_id, stemcell_cid, cloud_properties, networks, disk_cids = ni begin settings = agent_settings.initial_agent_settings( - bosh_vm_meta.agent_id, - networks, - environment, - vm_params, - @config + bosh_vm_meta.agent_id, + networks, + environment, + vm_params, + @config ) registry.update_settings(instance_id.to_s, settings) if _should_write_to_registry? @@ -620,7 +621,6 @@ def detach_disk(vm_cid, disk_cid) end with_thread_name("detach_disk(#{vm_cid},#{disk_cid})") do @telemetry_manager.monitor('detach_disk', id: vm_cid) do - if _should_write_to_registry? _update_agent_settings(vm_cid) do |settings| settings['disks'] ||= {} diff --git a/src/bosh_azure_cpi/lib/cloud/azure/disk/config_disk_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/disk/config_disk_manager.rb index bf3f5d6da..360bd8a11 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/disk/config_disk_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/disk/config_disk_manager.rb @@ -20,8 +20,7 @@ def initialize(blob_manager, disk_manager2, storage_account_manager) # Returns the config disk uri. def prepare_config_disk(resource_group_name, vm_name, location, metadata_obj, user_data_obj) - disk = _create_config_disk(resource_group_name, vm_name, location, metadata_obj, user_data_obj) - disk + _create_config_disk(resource_group_name, vm_name, location, metadata_obj, user_data_obj) end private diff --git a/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager.rb index 3edaee29a..399c30985 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class DiskManager + class DiskManager # rubocop:todo Metrics/ClassLength include Bosh::Exec include Helpers diff --git a/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager2.rb b/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager2.rb index 2c00c6916..be3f9dea1 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager2.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/disk/disk_manager2.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class DiskManager2 + class DiskManager2 # rubocop:todo Metrics/ClassLength include Bosh::Exec include Helpers diff --git a/src/bosh_azure_cpi/lib/cloud/azure/meta_store/stemcell_meta.rb b/src/bosh_azure_cpi/lib/cloud/azure/meta_store/stemcell_meta.rb index 1d12eabef..5bd3b3c4a 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/meta_store/stemcell_meta.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/meta_store/stemcell_meta.rb @@ -2,8 +2,9 @@ module Bosh::AzureCloud class StemcellMeta - attr_reader :name, :storage_account_name, :status, :timestamp - attr_writer :status + attr_accessor :status + attr_reader :name, :storage_account_name, :timestamp + def initialize(name, storage_account_name, status, timestamp = nil) @name = name @storage_account_name = storage_account_name diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/bosh_vm_meta.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/bosh_vm_meta.rb index 371b90f8f..fe91dee0c 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/bosh_vm_meta.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/bosh_vm_meta.rb @@ -3,6 +3,7 @@ module Bosh::AzureCloud class BoshVMMeta attr_reader :agent_id, :stemcell_cid + def initialize(agent_id, stemcell_cid) @agent_id = agent_id @stemcell_cid = stemcell_cid diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/config.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/config.rb index 955125b9a..2a2c536a0 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/config.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/config.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud + # TODO: Refactoring: Move class to new file: LoadBalancerConfig class LoadBalancerConfig attr_reader :name, :resource_group_name, :backend_pool_name @@ -15,6 +16,7 @@ def to_s end end + # TODO: Refactoring: Move class to new file: ApplicationGatewayConfig class ApplicationGatewayConfig attr_reader :name, :resource_group_name, :backend_pool_name @@ -29,9 +31,11 @@ def to_s end end + # TODO: Refactoring: Move class to new file: AvailabilitySetConfig class AvailabilitySetConfig attr_reader :name attr_reader :platform_update_domain_count, :platform_fault_domain_count + def initialize(name, platform_update_domain_count, platform_fault_domain_count) @name = name @platform_update_domain_count = platform_update_domain_count @@ -43,9 +47,11 @@ def to_s end end + # TODO: Refactoring: Move class to new file: AzureStackConfig class AzureStackConfig - attr_reader :domain, :authentication, :resource, :endpoint_prefix - attr_writer :authentication + attr_accessor :authentication + attr_reader :domain, :resource, :endpoint_prefix + def initialize(azure_stack_config_hash) @domain = azure_stack_config_hash['domain'] @authentication = azure_stack_config_hash['authentication'] @@ -54,19 +60,24 @@ def initialize(azure_stack_config_hash) end end + # TODO: Refactoring: Move class to new file: ConfigDisk class ConfigDisk attr_reader :enabled + def initialize(config_disk_config_hash) @enabled = config_disk_config_hash['enabled'] end end + # TODO: Refactoring: Move class to new file: AzureConfig class AzureConfig include Helpers + attr_reader :environment, :subscription_id, :location, :resource_group_name attr_reader :azure_stack attr_reader :credentials_source, :tenant_id, :client_id, :client_secret, :default_managed_identity - attr_reader :use_managed_disks, :storage_account_name + attr_accessor :storage_account_name + attr_reader :use_managed_disks attr_reader :default_security_group attr_reader :enable_vm_boot_diagnostics, :is_debug_mode, :keep_failed_vms attr_reader :enable_telemetry, :isv_tracking_guid @@ -77,8 +88,6 @@ class AzureConfig attr_reader :stemcell_api_version attr_reader :use_default_account_for_cleaning - attr_writer :storage_account_name - def initialize(azure_config_hash) @environment = azure_config_hash['environment'] @environment == ENVIRONMENT_AZURESTACK && !azure_config_hash['azure_stack'].nil? && @azure_stack = AzureStackConfig.new(azure_config_hash['azure_stack']) @@ -134,6 +143,7 @@ def managed_identity_enabled? end end + # TODO: Refactoring: Move class to new file: RegistryConfig class RegistryConfig attr_reader :endpoint, :user, :password @@ -146,6 +156,7 @@ def initialize(registry_config_hash) end end + # TODO: Refactoring: Move class to new file: AgentConfig class AgentConfig def initialize(agent_config_hash) @config = agent_config_hash @@ -158,6 +169,7 @@ def to_h class Config attr_reader :azure, :registry, :agent + def initialize(config_hash) @config = config_hash @azure = AzureConfig.new(config_hash['azure'] || {}) diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/disk_id.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/disk_id.rb index e3f271b6c..8e0748643 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/disk_id.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/disk_id.rb @@ -78,12 +78,8 @@ def validate if @plain_id.nil? cloud_error("Invalid disk_name in disk id (version 2) '#{self}'") if disk_name.nil? || disk_name.empty? cloud_error("Invalid caching in disk id (version 2) '#{self}'") if caching.nil? || caching.empty? - unless resource_group_name.nil? - cloud_error("Invalid resource_group_name in disk id (version 2) '#{self}'") if resource_group_name.empty? - end - if disk_name.start_with?(DATA_DISK_PREFIX) - cloud_error("Invalid storage_account_name in disk id (version 2) '#{self}'") if storage_account_name.nil? || storage_account_name.empty? - end + cloud_error("Invalid resource_group_name in disk id (version 2) '#{self}'") if !resource_group_name.nil? && resource_group_name.empty? + cloud_error("Invalid storage_account_name in disk id (version 2) '#{self}'") if disk_name.start_with?(DATA_DISK_PREFIX) && (storage_account_name.nil? || storage_account_name.empty?) end end diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/ephemeral_disk.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/ephemeral_disk.rb index aad75ad0c..95b78e469 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/ephemeral_disk.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/ephemeral_disk.rb @@ -3,6 +3,7 @@ module Bosh::AzureCloud class EphemeralDisk attr_reader :use_root_disk, :size, :type + def initialize(use_root_disk, size, type) @use_root_disk = use_root_disk @size = size diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/instance_id.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/instance_id.rb index c281b5995..4641aca27 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/instance_id.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/instance_id.rb @@ -71,9 +71,7 @@ def validate else cloud_error("Invalid resource_group_name in instance id (version 2) '#{self}'") if resource_group_name.nil? || resource_group_name.empty? cloud_error("Invalid vm_name in instance id (version 2)' '#{self}'") if vm_name.nil? || vm_name.empty? - unless storage_account_name.nil? - cloud_error("Invalid storage_account_name in instance id (version 2) '#{self}'") if storage_account_name.empty? - end + cloud_error("Invalid storage_account_name in instance id (version 2) '#{self}'") if !storage_account_name.nil? && storage_account_name.empty? end end diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/root_disk.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/root_disk.rb index 43a460b47..010002922 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/root_disk.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/root_disk.rb @@ -3,6 +3,7 @@ module Bosh::AzureCloud class RootDisk attr_reader :size, :type + def initialize(size, type) @size = size @type = type diff --git a/src/bosh_azure_cpi/lib/cloud/azure/models/vm_cloud_props.rb b/src/bosh_azure_cpi/lib/cloud/azure/models/vm_cloud_props.rb index b6708c1af..0b4ae5fdf 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/models/vm_cloud_props.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/models/vm_cloud_props.rb @@ -2,7 +2,7 @@ module Bosh::AzureCloud # https://bosh.io/docs/azure-cpi/#resource-pools - class VMCloudProps + class VMCloudProps # rubocop:todo Metrics/ClassLength include Helpers attr_accessor :instance_type attr_reader :instance_types @@ -20,6 +20,8 @@ class VMCloudProps attr_reader :tags # Below defines are for test purpose + # NOTE: The following 3 attr_writer (and their paired readers above) are explicitly separate (instead of using `attr_accessor`) + # since they are (as noted above) for testing only, and in case they need to be removed/hidden later. attr_writer :availability_zone attr_writer :availability_set attr_writer :assign_dynamic_public_ip diff --git a/src/bosh_azure_cpi/lib/cloud/azure/restapi/azure_client.rb b/src/bosh_azure_cpi/lib/cloud/azure/restapi/azure_client.rb index 3c9def434..18e4bfaf8 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/restapi/azure_client.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/restapi/azure_client.rb @@ -14,6 +14,7 @@ class AzureNotFoundError < AzureError; end class AzureConflictError < AzureError; end class AzureInternalError < AzureError; end class AzureAsynInternalError < AzureError; end + class AzureAsynchronousError < AzureError attr_accessor :status, :error @@ -22,7 +23,7 @@ def initialize(status = nil) end end - class AzureClient + class AzureClient # rubocop:todo Metrics/ClassLength include Helpers HTTP_CODE_OK = 200 @@ -152,7 +153,7 @@ def get_resources_by_url(url, params = {}) next_url = body['nextLink'] end - while next_url != nil + until next_url.nil? @logger.debug("Getting resources from nextLink #{next_url}") uri = URI(next_url) response = http_get(uri) @@ -813,9 +814,7 @@ def get_availability_set(url) availability_set[:tags] = result['tags'] availability_set[:managed] = false - unless result['sku'].nil? - availability_set[:managed] = true if result['sku']['name'] == 'Aligned' - end + availability_set[:managed] = true if !result['sku'].nil? && (result['sku']['name'] == 'Aligned') properties = result['properties'] availability_set[:provisioning_state] = properties['provisioningState'] @@ -1266,7 +1265,7 @@ def create_public_ip(resource_group_name, params) } if params[:zone] public_ip['zones'] = [params[:zone]] - public_ip['sku'] = {'name' => 'Standard'} + public_ip['sku'] = { 'name' => 'Standard' } public_ip['properties']['publicIPAllocationMethod'] = 'Static' end @@ -1467,13 +1466,8 @@ def create_network_interface(resource_group_name, nic_params) # see: Bosh::AzureCloud::VMManager._get_load_balancers load_balancers = nic_params[:load_balancers] unless load_balancers.nil? - backend_pools = load_balancers.map { |load_balancer| {:id => load_balancer[:backend_address_pools][0][:id]} } - inbound_nat_rules = Array.new - load_balancers.each do |load_balancer| - unless load_balancer[:frontend_ip_configurations][0][:inbound_nat_rules].nil? - inbound_nat_rules += load_balancer[:frontend_ip_configurations][0][:inbound_nat_rules] - end - end + backend_pools = load_balancers.map { |load_balancer| { id: load_balancer[:backend_address_pools][0][:id] } } + inbound_nat_rules = load_balancers.flat_map { |load_balancer| load_balancer[:frontend_ip_configurations][0][:inbound_nat_rules] }.compact interface['properties']['ipConfigurations'][0]['properties']['loadBalancerBackendAddressPools'] = backend_pools interface['properties']['ipConfigurations'][0]['properties']['loadBalancerInboundNatRules'] = inbound_nat_rules end @@ -1482,7 +1476,7 @@ def create_network_interface(resource_group_name, nic_params) application_gateways = nic_params[:application_gateways] unless application_gateways.nil? # NOTE: backend_address_pools[0] should always be used. (When `application_gateway/backend_pool_name` is specified, the named pool will always be first here.) - backend_pools = application_gateways.map { |application_gateway| {:id => application_gateway[:backend_address_pools][0][:id]} } + backend_pools = application_gateways.map { |application_gateway| { id: application_gateway[:backend_address_pools][0][:id] } } interface['properties']['ipConfigurations'][0]['properties']['applicationGatewayBackendAddressPools'] = backend_pools end @@ -1852,12 +1846,11 @@ def check_storage_account_name_availability(name) result = http_post(url, storage_account) raise AzureError, "Cannot check the availability of the storage account name '#{name}'" unless result.is_a?(Hash) - ret = { + { available: result['nameAvailable'], reason: result['reason'], message: result['message'] } - ret end # Get a storage account's information @@ -1944,7 +1937,7 @@ def list_storage_accounts def update_tags_of_storage_account(name, tags) url = rest_api_url(REST_API_PROVIDER_STORAGE, REST_API_STORAGE_ACCOUNTS, name: name) request_body = { - "tags": tags + tags: tags } http_patch(url, request_body) end @@ -2132,9 +2125,8 @@ def parse_public_ip(result) ip_address[:name] = result['name'] ip_address[:location] = result['location'] ip_address[:tags] = result['tags'] - ip_address[:sku] = result['sku']['name'] unless result['sku'].nil? - - ip_address[:zone] = result['zones'][0] unless result['zones'].nil? + ip_address[:sku] = result['sku']['name'] unless result['sku'].nil? + ip_address[:zone] = result['zones'][0] unless result['zones'].nil? properties = result['properties'] ip_address[:resource_guid] = properties['resourceGuid'] @@ -2181,7 +2173,13 @@ def filter_credential_in_logs(uri) end def redact_credentials(keys, hash) - Hash[hash.map { |k, v| [k, v.is_a?(Hash) ? redact_credentials(keys, v) : (keys.include?(k) ? '' : v)] }] + hash.map do |k, v| + [k, if v.is_a?(Hash) + redact_credentials(keys, v) + else + (keys.include?(k) ? '' : v) + end] + end.to_h end # @return [String] @@ -2200,9 +2198,9 @@ def redact_credentials_in_response_body(body) def http(uri, use_ssl = true) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true && use_ssl - if @azure_config.environment == ENVIRONMENT_AZURESTACK + if @azure_config.environment == ENVIRONMENT_AZURESTACK && uri.host.include?(@azure_config.azure_stack.domain) # The CA cert is only specified for the requests to AzureStack domain. If specified for other domains, the request will fail. - http.ca_file = get_ca_cert_path if uri.host.include?(@azure_config.azure_stack.domain) + http.ca_file = get_ca_cert_path end # The default value for read_timeout is 60 seconds. # The default value for open_timeout is nil before ruby 2.3.0 so set it to 60 seconds here. @@ -2243,11 +2241,12 @@ def get_token(force_refresh = false) end end - if status_code == HTTP_CODE_OK + case status_code + when HTTP_CODE_OK @token = JSON(response.body) - elsif status_code == HTTP_CODE_UNAUTHORIZED + when HTTP_CODE_UNAUTHORIZED raise AzureError, "get_token - http code: #{status_code}. Azure authentication failed: Invalid tenant_id, client_id or client_secret/certificate. Error message: #{response.body}" - elsif status_code == HTTP_CODE_BAD_REQUEST + when HTTP_CODE_BAD_REQUEST raise AzureError, "get_token - http code: #{status_code}. Azure authentication failed: Bad request. Please assure no typo in values of tenant_id, client_id or client_secret/certificate. Error message: #{response.body}" else raise AzureError, "get_token - http code: #{status_code}. Error message: #{response.body}" @@ -2467,9 +2466,10 @@ def check_completion(response, options) raise AzureAsynchronousError.new, "The body of the asynchronous response does not contain 'status'. Response: #{response.body}" if result['status'].nil? status = result['status'] - if status == PROVISIONING_STATE_SUCCEEDED + case status + when PROVISIONING_STATE_SUCCEEDED return true - elsif status == PROVISIONING_STATE_INPROGRESS + when PROVISIONING_STATE_INPROGRESS @logger.debug('check_completion - InProgress...') else error = "check_completion - http code: #{response.code}\n" diff --git a/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager.rb index b29e678c6..52f434a7f 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class StemcellManager + class StemcellManager # rubocop:todo Metrics/ClassLength STEMCELL_STATUS_PENDING = 'pending' STEMCELL_STATUS_SUCCESS = 'success' DEFAULT_COPY_STEMCELL_TIMEOUT = 20 * 60 # seconds diff --git a/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager2.rb b/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager2.rb index 49dba07c7..4b07db4a4 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager2.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/stemcell/stemcell_manager2.rb @@ -25,7 +25,7 @@ def delete_stemcell(name) end if @storage_account_manager.use_default_account_for_cleaning - # Delete a stemcell name in defaukt storage accounts + # Delete a stemcell name in default storage accounts @logger.info("Delete stemcell(#{name}) in default storage account #{@default_storage_account_name}") @blob_manager.delete_blob(@default_storage_account_name, STEMCELL_CONTAINER, "#{name}.vhd") if has_stemcell?(@default_storage_account_name, name) else diff --git a/src/bosh_azure_cpi/lib/cloud/azure/storage/blob_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/storage/blob_manager.rb index 7cea13b0f..65ff55abb 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/storage/blob_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/storage/blob_manager.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class BlobManager + class BlobManager # rubocop:todo Metrics/ClassLength include Helpers MAX_CHUNK_SIZE = 2 * 1024 * 1024 # 2MB @@ -37,7 +37,7 @@ def get_sas_blob_uri(storage_account_name, container_name, blob_name) token = generator.generate_service_sas_token( "#{container_name}/#{blob_name}", service: 'b', resource: 'b', permissions: 'r', protocol: 'https', - expiry: (Time.new + 3600 * 24 * 7).utc.iso8601 # one week is enough for copy blob and so on. + expiry: (Time.new + (3600 * 24 * 7)).utc.iso8601 # one week is enough for copy blob and so on. ) "#{@azure_storage_client.storage_blob_host}/#{container_name}/#{blob_name}?#{token}" end @@ -94,17 +94,15 @@ def create_page_blob(storage_account_name, container_name, file_path, blob_name, def create_empty_page_blob(storage_account_name, container_name, blob_name, blob_size_in_kb, metadata) @logger.info("create_empty_page_blob(#{storage_account_name}, #{container_name}, #{blob_name}, #{blob_size_in_kb}, #{metadata})") _initialize_blob_client(storage_account_name) do - begin - options = { - timeout: TIMEOUT_FOR_BLOB_OPERATIONS, - metadata: encode_metadata(metadata) - } - blob_size = blob_size_in_kb * 1024 - @logger.info("create_empty_page_blob: Calling _create_page_blob(#{container_name}, #{blob_name}, #{blob_size}, #{options})") - _create_page_blob(container_name, blob_name, blob_size, options) - rescue StandardError => e - cloud_error("Failed to create empty page blob: inspect:#{e.inspect}\n backtrace:#{e.backtrace.join("\n")}") - end + options = { + timeout: TIMEOUT_FOR_BLOB_OPERATIONS, + metadata: encode_metadata(metadata) + } + blob_size = blob_size_in_kb * 1024 + @logger.info("create_empty_page_blob: Calling _create_page_blob(#{container_name}, #{blob_name}, #{blob_size}, #{options})") + _create_page_blob(container_name, blob_name, blob_size, options) + rescue StandardError => e + cloud_error("Failed to create empty page blob: inspect:#{e.inspect}\n backtrace:#{e.backtrace.join("\n")}") end end @@ -156,63 +154,57 @@ def create_empty_vhd_blob(storage_account_name, container_name, blob_name, blob_ @logger.info("create_empty_vhd_blob(#{storage_account_name}, #{container_name}, #{blob_name}, #{blob_size_in_gb})") blob_created = false _initialize_blob_client(storage_account_name) do - begin - @logger.info('create_empty_vhd_blob: Start to generate vhd footer') - vhd_size = blob_size_in_gb * 1024 * 1024 * 1024 + @logger.info('create_empty_vhd_blob: Start to generate vhd footer') + vhd_size = blob_size_in_gb * 1024 * 1024 * 1024 - vhd_footer = VHDUtils.generate_footer(vhd_size).values.join - blob_size = vhd_size + 512 - options = { - timeout: TIMEOUT_FOR_BLOB_OPERATIONS - } - @logger.info("create_empty_vhd_blob: Calling _create_page_blob(#{container_name}, #{blob_name}, #{blob_size}, #{options})") - _create_page_blob(container_name, blob_name, blob_size, options) - blob_created = true + vhd_footer = VHDUtils.generate_footer(vhd_size).values.join + blob_size = vhd_size + 512 + options = { + timeout: TIMEOUT_FOR_BLOB_OPERATIONS + } + @logger.info("create_empty_vhd_blob: Calling _create_page_blob(#{container_name}, #{blob_name}, #{blob_size}, #{options})") + _create_page_blob(container_name, blob_name, blob_size, options) + blob_created = true - @logger.info('create_empty_vhd_blob: Start to upload vhd footer') + @logger.info('create_empty_vhd_blob: Start to upload vhd footer') - options = merge_storage_common_options(options) - # Do not log vhd_footer because its size is 512 bytes. - @logger.info("create_empty_vhd_blob: Calling put_blob_pages(#{container_name}, #{blob_name}, #{vhd_size}, #{blob_size - 1}, [VHD-FOOTER], #{options})") - @blob_service_client.put_blob_pages(container_name, blob_name, vhd_size, blob_size - 1, vhd_footer, options) - rescue StandardError => e - if blob_created - options = merge_storage_common_options - @logger.info("create_empty_vhd_blob: Calling delete_blob(#{container_name}, #{blob_name}, #{options})") - @blob_service_client.delete_blob(container_name, blob_name, options) - end - cloud_error("create_empty_vhd_blob: Failed to create empty vhd blob: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") + options = merge_storage_common_options(options) + # Do not log vhd_footer because its size is 512 bytes. + @logger.info("create_empty_vhd_blob: Calling put_blob_pages(#{container_name}, #{blob_name}, #{vhd_size}, #{blob_size - 1}, [VHD-FOOTER], #{options})") + @blob_service_client.put_blob_pages(container_name, blob_name, vhd_size, blob_size - 1, vhd_footer, options) + rescue StandardError => e + if blob_created + options = merge_storage_common_options + @logger.info("create_empty_vhd_blob: Calling delete_blob(#{container_name}, #{blob_name}, #{options})") + @blob_service_client.delete_blob(container_name, blob_name, options) end + cloud_error("create_empty_vhd_blob: Failed to create empty vhd blob: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") end end def get_blob_properties(storage_account_name, container_name, blob_name) @logger.info("get_blob_properties(#{storage_account_name}, #{container_name}, #{blob_name})") _initialize_blob_client(storage_account_name) do - begin - options = merge_storage_common_options - @logger.info("get_blob_properties: Calling get_blob_properties(#{container_name}, #{blob_name}, #{options})") - blob = @blob_service_client.get_blob_properties(container_name, blob_name, options) - blob.properties - rescue StandardError => e - cloud_error("get_blob_properties: #{e.inspect}\n#{e.backtrace.join("\n")}") unless e.message.include?('(404)') - nil - end + options = merge_storage_common_options + @logger.info("get_blob_properties: Calling get_blob_properties(#{container_name}, #{blob_name}, #{options})") + blob = @blob_service_client.get_blob_properties(container_name, blob_name, options) + blob.properties + rescue StandardError => e + cloud_error("get_blob_properties: #{e.inspect}\n#{e.backtrace.join("\n")}") unless e.message.include?('(404)') + nil end end def get_blob_metadata(storage_account_name, container_name, blob_name) @logger.info("get_blob_metadata(#{storage_account_name}, #{container_name}, #{blob_name})") _initialize_blob_client(storage_account_name) do - begin - options = merge_storage_common_options - @logger.info("get_blob_metadata: Calling get_blob_metadata(#{container_name}, #{blob_name}, #{options})") - blob = @blob_service_client.get_blob_metadata(container_name, blob_name, options) - blob.metadata - rescue StandardError => e - cloud_error("get_blob_metadata: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") unless e.message.include?('(404)') - nil - end + options = merge_storage_common_options + @logger.info("get_blob_metadata: Calling get_blob_metadata(#{container_name}, #{blob_name}, #{options})") + blob = @blob_service_client.get_blob_metadata(container_name, blob_name, options) + blob.metadata + rescue StandardError => e + cloud_error("get_blob_metadata: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") unless e.message.include?('(404)') + nil end end @@ -220,13 +212,11 @@ def get_blob_metadata(storage_account_name, container_name, blob_name) def set_blob_metadata(storage_account_name, container_name, blob_name, metadata) @logger.info("set_blob_metadata(#{storage_account_name}, #{container_name}, #{blob_name}, #{metadata})") _initialize_blob_client(storage_account_name) do - begin - options = merge_storage_common_options - @logger.info("set_blob_metadata: Calling set_blob_metadata(#{container_name}, #{blob_name}, #{metadata}, #{options})") - @blob_service_client.set_blob_metadata(container_name, blob_name, encode_metadata(metadata), options) - rescue StandardError => e - cloud_error("set_blob_metadata: Failed to set the metadata for the blob: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") - end + options = merge_storage_common_options + @logger.info("set_blob_metadata: Calling set_blob_metadata(#{container_name}, #{blob_name}, #{metadata}, #{options})") + @blob_service_client.set_blob_metadata(container_name, blob_name, encode_metadata(metadata), options) + rescue StandardError => e + cloud_error("set_blob_metadata: Failed to set the metadata for the blob: inspect:#{e.inspect}\nbacktrace:#{e.backtrace.join("\n")}") end end @@ -269,49 +259,47 @@ def snapshot_blob(storage_account_name, container_name, blob_name, metadata) def copy_blob(storage_account_name, container_name, blob_name, source_blob_uri) @logger.info("copy_blob(#{storage_account_name}, #{container_name}, #{blob_name}, #{source_blob_uri})") _initialize_blob_client(storage_account_name) do - begin - start_time = Time.new + start_time = Time.new + options = merge_storage_common_options + @logger.info("copy_blob: Calling _copy_blob_from_uri(#{container_name}, #{blob_name}, #{source_blob_uri}, #{options})") + copy_id, copy_status = _copy_blob_from_uri(container_name, blob_name, source_blob_uri, options) + @logger.info("copy_blob: x-ms-copy-id: #{copy_id}, x-ms-copy-status: #{copy_status}") + + copy_status_description = '' + while copy_status == 'pending' options = merge_storage_common_options - @logger.info("copy_blob: Calling _copy_blob_from_uri(#{container_name}, #{blob_name}, #{source_blob_uri}, #{options})") - copy_id, copy_status = _copy_blob_from_uri(container_name, blob_name, source_blob_uri, options) - @logger.info("copy_blob: x-ms-copy-id: #{copy_id}, x-ms-copy-status: #{copy_status}") - - copy_status_description = '' - while copy_status == 'pending' - options = merge_storage_common_options - @logger.info("copy_blob: Calling get_blob_properties(#{container_name}, #{blob_name}, #{options})") - blob = @blob_service_client.get_blob_properties(container_name, blob_name, options) - blob_props = blob.properties - cloud_error("copy_blob: The progress of copying the blob #{source_blob_uri} to #{container_name}/#{blob_name} was interrupted by other copy operations.") if !copy_id.nil? && blob_props[:copy_id] != copy_id - - copy_status_description = blob_props[:copy_status_description] - copy_status = blob_props[:copy_status] - break if copy_status != 'pending' - - @logger.debug("copy_blob: Copying progress: #{blob_props[:copy_progress]}") - elapse_time = Time.new - start_time - copied_bytes, total_bytes = blob_props[:copy_progress].split('/').map(&:to_i) - interval = copied_bytes.zero? ? 5 : (total_bytes - copied_bytes).to_f / copied_bytes * elapse_time - interval = 30 if interval > 30 - interval = 1 if interval < 1 - sleep(interval) - end + @logger.info("copy_blob: Calling get_blob_properties(#{container_name}, #{blob_name}, #{options})") + blob = @blob_service_client.get_blob_properties(container_name, blob_name, options) + blob_props = blob.properties + cloud_error("copy_blob: The progress of copying the blob #{source_blob_uri} to #{container_name}/#{blob_name} was interrupted by other copy operations.") if !copy_id.nil? && blob_props[:copy_id] != copy_id + + copy_status_description = blob_props[:copy_status_description] + copy_status = blob_props[:copy_status] + break if copy_status != 'pending' + + @logger.debug("copy_blob: Copying progress: #{blob_props[:copy_progress]}") + elapse_time = Time.new - start_time + copied_bytes, total_bytes = blob_props[:copy_progress].split('/').map(&:to_i) + interval = copied_bytes.zero? ? 5 : (total_bytes - copied_bytes).to_f / copied_bytes * elapse_time + interval = 30 if interval > 30 + interval = 1 if interval < 1 + sleep(interval) + end - if copy_status == 'success' - duration = Time.new - start_time - @logger.info("copy_blob: Copy the blob #{source_blob_uri} successfully. Duration: #{duration.inspect}") - else - cloud_error("copy_blob: Failed to copy the blob #{source_blob_uri}: \n\tcopy status: #{copy_status}\n\tcopy description: #{copy_status_description}") - end - rescue StandardError => e - ignore_exception do - options = merge_storage_common_options - @logger.info("copy_blob: Calling delete_blob(#{container_name}, #{blob_name}, #{options})") - @blob_service_client.delete_blob(container_name, blob_name, options) - @logger.info("copy_blob: Delete the blob #{container_name}/#{blob_name}") - end - raise e + if copy_status == 'success' + duration = Time.new - start_time + @logger.info("copy_blob: Copy the blob #{source_blob_uri} successfully. Duration: #{duration.inspect}") + else + cloud_error("copy_blob: Failed to copy the blob #{source_blob_uri}: \n\tcopy status: #{copy_status}\n\tcopy description: #{copy_status_description}") end + rescue StandardError => e + ignore_exception do + options = merge_storage_common_options + @logger.info("copy_blob: Calling delete_blob(#{container_name}, #{blob_name}, #{options})") + @blob_service_client.delete_blob(container_name, blob_name, options) + @logger.info("copy_blob: Delete the blob #{container_name}/#{blob_name}") + end + raise e end end diff --git a/src/bosh_azure_cpi/lib/cloud/azure/storage/storage_account_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/storage/storage_account_manager.rb index eed074567..ce40c2e7e 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/storage/storage_account_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/storage/storage_account_manager.rb @@ -1,10 +1,11 @@ # frozen_string_literal: true module Bosh::AzureCloud - class StorageAccountManager + class StorageAccountManager # rubocop:todo Metrics/ClassLength include Helpers attr_reader :use_default_account_for_cleaning + def initialize(azure_config, blob_manager, azure_client) @azure_config = azure_config @blob_manager = blob_manager diff --git a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event.rb b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event.rb index 77efd54c5..46247b2ab 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event.rb @@ -19,8 +19,8 @@ def to_hash { 'name' => @name, 'value' => @value } end - def to_json - to_hash.to_json + def to_json(*args) + to_hash.to_json(*args) end def to_xml @@ -116,8 +116,8 @@ def to_hash } end - def to_json - to_hash.to_json + def to_json(*args) + to_hash.to_json(*args) end # this function is only used in TelemetryEventList which will group the events by provider_id @@ -161,7 +161,7 @@ def to_xml end xml_string_grouped_by_providers = '' - events_grouped_by_provider.keys.each do |provider_id| + events_grouped_by_provider.each_key do |provider_id| xml_string = '' events_grouped_by_provider[provider_id].each do |event| xml_string += event.to_xml_without_provider diff --git a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event_handler.rb b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event_handler.rb index d5c61cd24..77d769f0b 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event_handler.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/telemetry_event_handler.rb @@ -55,15 +55,13 @@ def collect_events(max = 4) event_files = Dir["#{@events_dir}/*.tld"] event_files = event_files[0...max] if event_files.length > max event_files.each do |file| - begin - hash = JSON.parse(File.read(file)) - event_list << Bosh::AzureCloud::TelemetryEvent.parse_hash(hash) - rescue StandardError => e - @logger.warn("[Telemetry] Failed to collect event from '#{file}'. Error:\n#{e.inspect}\n#{e.backtrace.join("\n")}") - raise e - ensure - File.delete(file) - end + hash = JSON.parse(File.read(file)) + event_list << Bosh::AzureCloud::TelemetryEvent.parse_hash(hash) + rescue StandardError => e + @logger.warn("[Telemetry] Failed to collect event from '#{file}'. Error:\n#{e.inspect}\n#{e.backtrace.join("\n")}") + raise e + ensure + File.delete(file) end Bosh::AzureCloud::TelemetryEventList.new(event_list) end diff --git a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/wire_client.rb b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/wire_client.rb index bfb52e509..e9acb37e5 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/telemetry/wire_client.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/telemetry/wire_client.rb @@ -3,7 +3,7 @@ module Bosh::AzureCloud class RetriableError < RuntimeError; end - class WireClient + class WireClient # rubocop:todo Metrics/ClassLength TELEMETRY_URI_FORMAT = 'http://%{endpoint}/machine?comp=telemetrydata' TELEMETRY_HEADER = { 'Content-Type' => 'text/xml;charset=utf-8', 'x-ms-version' => '2012-11-30' }.freeze @@ -40,7 +40,7 @@ def post_data(event_list) begin request = Net::HTTP::Post.new(uri) request.body = event_list.format_data_for_wire_server - TELEMETRY_HEADER.keys.each do |key| + TELEMETRY_HEADER.each_key do |key| request[key] = TELEMETRY_HEADER[key] end res = Net::HTTP.new(uri.host, uri.port, nil).start { |http| http.request request } diff --git a/src/bosh_azure_cpi/lib/cloud/azure/utils/bosh_agent_util.rb b/src/bosh_azure_cpi/lib/cloud/azure/utils/bosh_agent_util.rb index 121e4018e..ba9db3da5 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/utils/bosh_agent_util.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/utils/bosh_agent_util.rb @@ -73,8 +73,8 @@ def user_data_obj(registry_endpoint, instance_id, dns, agent_id, network_spec, e def meta_data_obj(instance_id, ssh_public_key) user_data_obj = { instance_id: instance_id } user_data_obj[:'public-keys'] = { - "0": { - "openssh-key": ssh_public_key + '0': { + 'openssh-key': ssh_public_key } } user_data_obj diff --git a/src/bosh_azure_cpi/lib/cloud/azure/utils/helpers.rb b/src/bosh_azure_cpi/lib/cloud/azure/utils/helpers.rb index fd6a594f7..505096ce3 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/utils/helpers.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/utils/helpers.rb @@ -238,13 +238,14 @@ def get_azure_authentication_endpoint_and_api_version(azure_config) domain = azure_config.azure_stack.domain authentication = azure_config.azure_stack.authentication - if authentication == AZURESTACK_AUTHENTICATION_TYPE_AZUREAD + case authentication + when AZURESTACK_AUTHENTICATION_TYPE_AZUREAD url = "#{AZURE_ENVIRONMENTS[ENVIRONMENT_AZURECLOUD]['activeDirectoryEndpointUrl']}/#{azure_config.tenant_id}/oauth2/token" api_version = AZURE_ENVIRONMENTS[ENVIRONMENT_AZURECLOUD]['apiVersion'][AZURE_RESOURCE_PROVIDER_ACTIVEDIRECTORY] - elsif authentication == AZURESTACK_AUTHENTICATION_TYPE_AZURECHINACLOUDAD + when AZURESTACK_AUTHENTICATION_TYPE_AZURECHINACLOUDAD url = "#{AZURE_ENVIRONMENTS[ENVIRONMENT_AZURECHINACLOUD]['activeDirectoryEndpointUrl']}/#{azure_config.tenant_id}/oauth2/token" api_version = AZURE_ENVIRONMENTS[ENVIRONMENT_AZURECHINACLOUD]['apiVersion'][AZURE_RESOURCE_PROVIDER_ACTIVEDIRECTORY] - elsif authentication == AZURESTACK_AUTHENTICATION_TYPE_ADFS + when AZURESTACK_AUTHENTICATION_TYPE_ADFS url = "https://adfs.#{domain}/adfs/oauth2/token" else cloud_error("No support for the AzureStack authentication: '#{authentication}'") @@ -274,17 +275,17 @@ def get_jwt_assertion(authentication_endpoint, client_id) thumbprint = OpenSSL::Digest::SHA1.new(cert.to_der).to_s @logger.debug("The certificate thumbprint is '#{thumbprint}'") header = { - "alg": 'RS256', - "typ": 'JWT', - "x5t": Base64.urlsafe_encode64([thumbprint].pack('H*')) + alg: 'RS256', + typ: 'JWT', + x5t: Base64.urlsafe_encode64([thumbprint].pack('H*')) } payload = { - "aud": authentication_endpoint, - "exp": (Time.new + 3600).strftime('%s').to_i, - "iss": client_id, - "jti": SecureRandom.uuid, - "nbf": (Time.new - 90).strftime('%s').to_i, - "sub": client_id + aud: authentication_endpoint, + exp: (Time.new + 3600).strftime('%s').to_i, + iss: client_id, + jti: SecureRandom.uuid, + nbf: (Time.new - 90).strftime('%s').to_i, + sub: client_id } rsa_private = OpenSSL::PKey::RSA.new(certificate_data) JWT.encode(payload, rsa_private, 'RS256', header) @@ -296,7 +297,7 @@ def initialize_azure_storage_client(storage_account, azure_config) options = { storage_account_name: storage_account[:name], storage_access_key: storage_account[:key], - storage_dns_suffix: URI.parse(storage_account[:storage_blob_host]).host.split('.')[2..-1].join('.'), + storage_dns_suffix: URI.parse(storage_account[:storage_blob_host]).host.split('.')[2..].join('.'), user_agent_prefix: USER_AGENT_FOR_REST } options[:ca_file] = get_ca_cert_path if azure_config.environment == ENVIRONMENT_AZURESTACK @@ -338,7 +339,7 @@ def merge_storage_common_options(options = {}) # If the size is larger than 1,000 GiB, CPI uses 1,000 GiB because it is not expected to use such a large ephemeral disk in CF currently. You can find the temporary disk size in the comment if it is larger than 1,000 GiB # count: The maximum number of data disks for the instance type # The maximum number of data disks on Azure for now is 64. Set it to 64 if instance_type cannot be found in case a new instance type is supported in future - class DiskInfo + class DiskInfo # rubocop:todo Metrics/ClassLength INSTANCE_TYPE_DISK_MAPPING = { # A-series 'STANDARD_A0' => [30, 1], # 20 GiB @@ -585,15 +586,16 @@ def get_storage_account_type_by_instance_type(instance_type) def support_premium_storage?(instance_type) instance_type = instance_type.downcase - ((instance_type =~ /^standard_ds/) == 0) || # including DS and DSv2, e.g. Standard_DS1, Standard_DS1_v2 - ((instance_type =~ /^standard_d(\d)+s_v3/) == 0) || - ((instance_type =~ /^standard_gs/) == 0) || - ((instance_type =~ /^standard_b(\d)+s/) == 0) || - ((instance_type =~ /^standard_b(\d)+ms/) == 0) || - ((instance_type =~ /^standard_f(\d)+s/) == 0) || - ((instance_type =~ /^standard_e(\d)+s_v3/) == 0) || - ((instance_type =~ /^standard_e(\d)+is_v3/) == 0) || - ((instance_type =~ /^standard_l(\d)+s/) == 0) + # NOTE: The `Style/NumericPredicate` cop was reporting auto-correctable offenses for the lines below. But fixing the offenses caused failing specs, so the cop offenses have been disabled here. + ((instance_type =~ /^standard_ds/) == 0) || # including DS and DSv2, e.g. Standard_DS1, Standard_DS1_v2 # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_d(\d)+s_v3/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_gs/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_b(\d)+s/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_b(\d)+ms/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_f(\d)+s/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_e(\d)+s_v3/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_e(\d)+is_v3/) == 0) || # rubocop:disable Style/NumericPredicate + ((instance_type =~ /^standard_l(\d)+s/) == 0) # rubocop:disable Style/NumericPredicate end def is_stemcell_storage_account?(tags) @@ -621,7 +623,7 @@ def generate_windows_computer_name suffix = Process.pid.to_s(32) # default max pid 65536, .to_s(32) -> '2000' padding_length = WINDOWS_VM_NAME_LENGTH - prefix.length - suffix.length if padding_length >= 0 - prefix + '0' * padding_length + suffix + prefix + ('0' * padding_length) + suffix else @logger.warn('Length of generated string is longer than expected, so it is truncated. It may be not unique.') (prefix + suffix)[prefix.length + suffix.length - WINDOWS_VM_NAME_LENGTH, prefix.length + suffix.length] # get tail @@ -636,7 +638,7 @@ def validate_idle_timeout(idle_timeout_in_minutes) end def uri_escape(raw_uri) - CGI.escape(raw_uri).sub("%2F", "/") + CGI.escape(raw_uri).sub('%2F', '/') end end end diff --git a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager.rb b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager.rb index cc5e1f0d3..96ec77d1e 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class VMManager + class VMManager # rubocop:todo Metrics/ClassLength include Helpers def initialize(azure_config, registry_endpoint, disk_manager, disk_manager2, azure_client, storage_account_manager, stemcell_manager, stemcell_manager2, light_stemcell_manager, config_disk_manager = nil) @@ -184,7 +184,7 @@ def create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, en # Has upper characters # Has a digit # Has a special character (Regex match [\W_]) - vm_params[:windows_password] = "#{SecureRandom.uuid}#{SecureRandom.uuid.upcase}".split('').shuffle.join + vm_params[:windows_password] = "#{SecureRandom.uuid}#{SecureRandom.uuid.upcase}".chars.shuffle.join computer_name = generate_windows_computer_name vm_params[:computer_name] = computer_name vm_params[:custom_data] = agent_settings.encoded_user_data(@registry_endpoint, instance_id.to_s, network_configurator.default_dns, bosh_vm_meta.agent_id, network_spec, env, vm_params, config, computer_name) @@ -465,16 +465,14 @@ def _get_stemcell_info(stemcell_cid, vm_props, location, storage_account_name) raise Bosh::Clouds::VMCreationFailed.new(false), "Failed to get the user image information for the stemcell '#{stemcell_cid}': #{e.inspect}\n#{e.backtrace.join("\n")}" end end - else - if is_light_stemcell_cid?(stemcell_cid) - raise Bosh::Clouds::VMCreationFailed.new(false), "Given stemcell '#{stemcell_cid}' does not exist" unless @light_stemcell_manager.has_stemcell?(location, stemcell_cid) + elsif is_light_stemcell_cid?(stemcell_cid) + raise Bosh::Clouds::VMCreationFailed.new(false), "Given stemcell '#{stemcell_cid}' does not exist" unless @light_stemcell_manager.has_stemcell?(location, stemcell_cid) - stemcell_info = @light_stemcell_manager.get_stemcell_info(stemcell_cid) - else - raise Bosh::Clouds::VMCreationFailed.new(false), "Given stemcell '#{stemcell_cid}' does not exist" unless @stemcell_manager.has_stemcell?(storage_account_name, stemcell_cid) + stemcell_info = @light_stemcell_manager.get_stemcell_info(stemcell_cid) + else + raise Bosh::Clouds::VMCreationFailed.new(false), "Given stemcell '#{stemcell_cid}' does not exist" unless @stemcell_manager.has_stemcell?(storage_account_name, stemcell_cid) - stemcell_info = @stemcell_manager.get_stemcell_info(storage_account_name, stemcell_cid) - end + stemcell_info = @stemcell_manager.get_stemcell_info(storage_account_name, stemcell_cid) end @logger.debug("get_stemcell_info - got stemcell '#{stemcell_info.inspect}'") diff --git a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_availability_set.rb b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_availability_set.rb index 05595278e..960060481 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_availability_set.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_availability_set.rb @@ -6,17 +6,15 @@ class VMManager def _get_availability_set_name(vm_props, env) availability_set_name = vm_props.availability_set.name - if availability_set_name.nil? - unless env.nil? || env['bosh'].nil? || env['bosh']['group'].nil? - availability_set_name = env['bosh']['group'] + if availability_set_name.nil? && !(env.nil? || env['bosh'].nil? || env['bosh']['group'].nil?) + availability_set_name = env['bosh']['group'] - # https://github.com/cloudfoundry/bosh-azure-cpi-release/issues/209 - # On Azure the length of the availability set name must be between 1 and 80 characters. - # The group name which is generated by BOSH director may be too long. - # CPI will truncate the name to below format if the length is greater than 80. - # az-MD5-[LAST-40-CHARACTERS-OF-GROUP] - availability_set_name = "az-#{Digest::MD5.hexdigest(availability_set_name)}-#{availability_set_name[-40..-1]}" if availability_set_name.length > 80 - end + # https://github.com/cloudfoundry/bosh-azure-cpi-release/issues/209 + # On Azure the length of the availability set name must be between 1 and 80 characters. + # The group name which is generated by BOSH director may be too long. + # CPI will truncate the name to below format if the length is greater than 80. + # az-MD5-[LAST-40-CHARACTERS-OF-GROUP] + availability_set_name = "az-#{Digest::MD5.hexdigest(availability_set_name)}-#{availability_set_name[-40..]}" if availability_set_name.length > 80 end availability_set_name diff --git a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_network.rb b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_network.rb index fa059407c..f020c94fd 100644 --- a/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_network.rb +++ b/src/bosh_azure_cpi/lib/cloud/azure/vms/vm_manager_network.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module Bosh::AzureCloud - class VMManager + class VMManager # rubocop:todo Metrics/ClassLength private def _get_network_subnet(network) @@ -68,14 +68,12 @@ def _get_application_security_groups(vm_props, network) def _get_ip_forwarding(vm_props, network) # ip_forwarding can be specified in vm_types or vm_extensions and networks (ordered by priority) - ip_forwarding = vm_props.ip_forwarding.nil? ? network.ip_forwarding : vm_props.ip_forwarding - ip_forwarding + vm_props.ip_forwarding.nil? ? network.ip_forwarding : vm_props.ip_forwarding end def _get_accelerated_networking(vm_props, network) # accelerated_networking can be specified in vm_types or vm_extensions and networks (ordered by priority) - accelerated_networking = vm_props.accelerated_networking.nil? ? network.accelerated_networking : vm_props.accelerated_networking - accelerated_networking + vm_props.accelerated_networking.nil? ? network.accelerated_networking : vm_props.accelerated_networking end def _get_public_ip(vip_network) diff --git a/src/bosh_azure_cpi/spec/integration/azure_cpi_spec.rb b/src/bosh_azure_cpi/spec/integration/azure_cpi_spec.rb index e7729a84a..f9e373dd5 100644 --- a/src/bosh_azure_cpi/spec/integration/azure_cpi_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/azure_cpi_spec.rb @@ -11,7 +11,7 @@ @certificate = ENV.fetch('BOSH_AZURE_CERTIFICATE') end - before(:each) do + before do config_file.write(cloud_properties.to_yaml) config_file.close end @@ -84,7 +84,8 @@ let(:config_dir) { '/var/vcap/jobs/azure_cpi/config' } let(:certificate_path) { "#{config_dir}/service_principal_certificate.pem" } - before(:each) do + + before do FileUtils.mkdir_p(config_dir) File.open(certificate_path, 'wb') do |f| f.write(@certificate) @@ -133,7 +134,7 @@ result = run_cpi('method' => 'has_vm', 'arguments' => [SecureRandom.uuid.to_s], 'context' => { 'director_uuid' => 'abc123' }) expect(result.keys).to eq(%w[result error log]) expect(result['result']).to be_nil - expect(result['error']['message']).to match(%r{http code: 400. Azure authentication failed: Bad request. Please assure no typo in values of tenant_id, client_id or client_secret\/certificate}) + expect(result['error']['message']).to match(%r{http code: 400. Azure authentication failed: Bad request. Please assure no typo in values of tenant_id, client_id or client_secret/certificate}) expect(result['error']['ok_to_retry']).to be(false) expect(result['error']['type']).to eq('Bosh::AzureCloud::AzureError') expect(result['log']).to include('backtrace') @@ -172,7 +173,7 @@ result = run_cpi('method' => 'has_vm', 'arguments' => [SecureRandom.uuid.to_s], 'context' => { 'director_uuid' => 'abc123' }) expect(result.keys).to eq(%w[result error log]) expect(result['result']).to be_nil - expect(result['error']['message']).to match(%r{http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret\/certificate}) + expect(result['error']['message']).to match(%r{http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret/certificate}) expect(result['error']['ok_to_retry']).to be(false) expect(result['error']['type']).to eq('Bosh::AzureCloud::AzureError') expect(result['log']).to include('backtrace') @@ -233,14 +234,14 @@ it 'merges the context into the cloud_properties' do result = run_cpi('method' => 'has_vm', 'arguments' => [SecureRandom.uuid.to_s], 'context' => context) expect(result.keys).to eq(%w[result error log]) - expect(result['result']).to_not be_nil + expect(result['result']).not_to be_nil expect(result['result']).to be_falsey expect(result['error']).to be_nil end it 'returns the api version' do result = run_cpi('method' => 'info', 'arguments' => [], 'context' => context) - expect(result['result']).to_not be_nil + expect(result['result']).not_to be_nil expect(result['error']).to be_nil expect(result['result']['api_version']).to eq(2) end diff --git a/src/bosh_azure_cpi/spec/integration/lifecycle_spec.rb b/src/bosh_azure_cpi/spec/integration/lifecycle_spec.rb index b39e48352..ff8f34518 100644 --- a/src/bosh_azure_cpi/spec/integration/lifecycle_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/lifecycle_spec.rb @@ -5,7 +5,7 @@ describe Bosh::AzureCloud::Cloud do let(:extra_storage_account_name) { ENV.fetch('BOSH_AZURE_EXTRA_STORAGE_ACCOUNT_NAME', nil) } - context '#calculate_vm_cloud_properties' do + describe '#calculate_vm_cloud_properties' do let(:vm_resources) do { 'cpu' => 2, @@ -120,9 +120,9 @@ context 'and stemcell api version is 2' do it 'should not write to the registry' do - options['azure']['vm'] = { 'stemcell' => { 'api_version' => 2}} + options['azure']['vm'] = { 'stemcell' => { 'api_version' => 2 } } cpi = Bosh::AzureCloud::Cloud.new(options, 2) - expect(@registry).to_not receive(:update_settings) + expect(@registry).not_to receive(:update_settings) vm_lifecycle(stemcell_id: @stemcell_id, cpi: cpi) end end @@ -135,24 +135,24 @@ vm_lifecycle(stemcell_id: @stemcell_id, cpi: cpi) do |instance_id| disk = cpi.create_disk(1024, {}) result = cpi.attach_disk(instance_id, disk) - expect(result).to_not be_nil + expect(result).not_to be_nil expect(result).to be_a(Hash) - expect(result.keys).to eq(%w(lun host_device_id)) + expect(result.keys).to eq(%w[lun host_device_id]) end end context 'and stemcell api version 2' do it 'does not write to registry' do - options['azure']['vm'] = { 'stemcell' => { 'api_version' => 2}} + options['azure']['vm'] = { 'stemcell' => { 'api_version' => 2 } } cpi = Bosh::AzureCloud::Cloud.new(options, 2) - expect(@registry).to_not receive(:update_settings) + expect(@registry).not_to receive(:update_settings) vm_lifecycle(stemcell_id: @stemcell_id, cpi: cpi) do |instance_id| disk = cpi.create_disk(1024, {}) result = cpi.attach_disk(instance_id, disk) - expect(result).to_not be_nil + expect(result).not_to be_nil expect(result).to be_a(Hash) - expect(result.keys).to eq(%w(lun host_device_id)) + expect(result.keys).to eq(%w[lun host_device_id]) end end end diff --git a/src/bosh_azure_cpi/spec/integration/migrations/availability_zone_migration_spec.rb b/src/bosh_azure_cpi/spec/integration/migrations/availability_zone_migration_spec.rb index 82ecf86db..64c4219e0 100644 --- a/src/bosh_azure_cpi/spec/integration/migrations/availability_zone_migration_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/migrations/availability_zone_migration_spec.rb @@ -47,6 +47,7 @@ end before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") @@ -102,6 +103,7 @@ context 'when the regional VM is with managed disks' do let(:disk_id) { cpi_managed.create_disk(2048, {}, nil) } + before do # Create an regional disk expect(disk_id).not_to be_nil diff --git a/src/bosh_azure_cpi/spec/integration/migrations/managed_disks_migration_spec.rb b/src/bosh_azure_cpi/spec/integration/migrations/managed_disks_migration_spec.rb index c15668b5d..73a7b2f25 100644 --- a/src/bosh_azure_cpi/spec/integration/migrations/managed_disks_migration_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/migrations/managed_disks_migration_spec.rb @@ -36,6 +36,7 @@ end before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") @@ -58,73 +59,71 @@ context 'Without availability set' do it 'should exercise the vm lifecycle' do - begin - # Create an unmanaged VM - @logger.info("Creating unmanaged VM with stemcell_id='#{@stemcell_id}'") - unmanaged_instance_id, _ = cpi_unmanaged.create_vm(SecureRandom.uuid, @stemcell_id, vm_properties, network_spec) - @logger.info("Checking unmanaged VM existence instance_id='#{unmanaged_instance_id}'") - expect(cpi_unmanaged.has_vm?(unmanaged_instance_id)).to be(true) - @logger.info("Setting VM metadata instance_id='#{unmanaged_instance_id}'") - cpi_unmanaged.set_vm_metadata(unmanaged_instance_id, @vm_metadata) - cpi_unmanaged.reboot_vm(unmanaged_instance_id) - - # Create an unmanaged disk, and attach it to the unmanaged VM - disk_id = cpi_unmanaged.create_disk(2048, {}, unmanaged_instance_id) - expect(disk_id).not_to be_nil - @disk_id_pool.push(disk_id) - cpi_unmanaged.attach_disk(unmanaged_instance_id, disk_id) - - # Create and delete an unmanaged snapshot - unmanaged_snapshot_id = cpi_unmanaged.snapshot_disk(disk_id, snapshot_metadata) - expect(unmanaged_snapshot_id).not_to be_nil - cpi_unmanaged.delete_snapshot(unmanaged_snapshot_id) - - @logger.info('Assume that the new BOSH director (use_managed_disks=true) is deployed.') # After this line, cpi instead of cpi_unmanaged will be used - - # Even use_managed_disks is enabled, but the unmanaged VM and disks have not been updated. It should succeed to snapshot the unmanaged disk. - unmanaged_snapshot_id = cpi_managed.snapshot_disk(disk_id, snapshot_metadata) - expect(unmanaged_snapshot_id).not_to be_nil - cpi_managed.delete_snapshot(unmanaged_snapshot_id) - - @logger.info('The new BOSH director starts to update the unmanaged VM to a managed VM') - - # Detach the unmanaged disk - Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: ->(n, _) { [2**(n - 1), 30].min }) do - cpi_managed.detach_disk(unmanaged_instance_id, disk_id) - true - end - - # Delete the unmanaged VM - cpi_managed.delete_vm(unmanaged_instance_id) + # Create an unmanaged VM + @logger.info("Creating unmanaged VM with stemcell_id='#{@stemcell_id}'") + unmanaged_instance_id, _ = cpi_unmanaged.create_vm(SecureRandom.uuid, @stemcell_id, vm_properties, network_spec) + @logger.info("Checking unmanaged VM existence instance_id='#{unmanaged_instance_id}'") + expect(cpi_unmanaged.has_vm?(unmanaged_instance_id)).to be(true) + @logger.info("Setting VM metadata instance_id='#{unmanaged_instance_id}'") + cpi_unmanaged.set_vm_metadata(unmanaged_instance_id, @vm_metadata) + cpi_unmanaged.reboot_vm(unmanaged_instance_id) + + # Create an unmanaged disk, and attach it to the unmanaged VM + disk_id = cpi_unmanaged.create_disk(2048, {}, unmanaged_instance_id) + expect(disk_id).not_to be_nil + @disk_id_pool.push(disk_id) + cpi_unmanaged.attach_disk(unmanaged_instance_id, disk_id) + + # Create and delete an unmanaged snapshot + unmanaged_snapshot_id = cpi_unmanaged.snapshot_disk(disk_id, snapshot_metadata) + expect(unmanaged_snapshot_id).not_to be_nil + cpi_unmanaged.delete_snapshot(unmanaged_snapshot_id) + + @logger.info('Assume that the new BOSH director (use_managed_disks=true) is deployed.') # After this line, cpi instead of cpi_unmanaged will be used + + # Even use_managed_disks is enabled, but the unmanaged VM and disks have not been updated. It should succeed to snapshot the unmanaged disk. + unmanaged_snapshot_id = cpi_managed.snapshot_disk(disk_id, snapshot_metadata) + expect(unmanaged_snapshot_id).not_to be_nil + cpi_managed.delete_snapshot(unmanaged_snapshot_id) + + @logger.info('The new BOSH director starts to update the unmanaged VM to a managed VM') + + # Detach the unmanaged disk + Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: ->(n, _) { [2**(n - 1), 30].min }) do + cpi_managed.detach_disk(unmanaged_instance_id, disk_id) + true + end - # Create a managed VM - @logger.info("Creating managed VM with stemcell_id='#{@stemcell_id}'") - managed_instance_id, _ = cpi_managed.create_vm(SecureRandom.uuid, @stemcell_id, vm_properties, network_spec) - @logger.info("Checking managed VM existence instance_id='#{managed_instance_id}'") - expect(cpi_managed.has_vm?(managed_instance_id)).to be(true) + # Delete the unmanaged VM + cpi_managed.delete_vm(unmanaged_instance_id) - # Migrate the unmanaged disk to a managed disk, and attach the managed disk to the managed VM. The disk_id won't be changed. - cpi_managed.attach_disk(managed_instance_id, disk_id) + # Create a managed VM + @logger.info("Creating managed VM with stemcell_id='#{@stemcell_id}'") + managed_instance_id, _ = cpi_managed.create_vm(SecureRandom.uuid, @stemcell_id, vm_properties, network_spec) + @logger.info("Checking managed VM existence instance_id='#{managed_instance_id}'") + expect(cpi_managed.has_vm?(managed_instance_id)).to be(true) - # Create and delete a managed snapshot - managed_snapshot_id = cpi_managed.snapshot_disk(disk_id, snapshot_metadata) - expect(managed_snapshot_id).not_to be_nil - cpi_managed.delete_snapshot(managed_snapshot_id) + # Migrate the unmanaged disk to a managed disk, and attach the managed disk to the managed VM. The disk_id won't be changed. + cpi_managed.attach_disk(managed_instance_id, disk_id) - # Detach the managed disk - Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: ->(n, _) { [2**(n - 1), 30].min }) do - cpi_managed.detach_disk(managed_instance_id, disk_id) - true - end + # Create and delete a managed snapshot + managed_snapshot_id = cpi_managed.snapshot_disk(disk_id, snapshot_metadata) + expect(managed_snapshot_id).not_to be_nil + cpi_managed.delete_snapshot(managed_snapshot_id) - # Delete the managed disk, and the migrated unmanaged disk - cpi_managed.delete_disk(disk_id) - cpi_unmanaged.delete_disk(disk_id) - @disk_id_pool.delete(disk_id) - ensure - cpi_unmanaged.delete_vm(unmanaged_instance_id) unless unmanaged_instance_id.nil? - cpi_managed.delete_vm(managed_instance_id) unless managed_instance_id.nil? + # Detach the managed disk + Bosh::Common.retryable(tries: 20, on: Bosh::Clouds::DiskNotAttached, sleep: ->(n, _) { [2**(n - 1), 30].min }) do + cpi_managed.detach_disk(managed_instance_id, disk_id) + true end + + # Delete the managed disk, and the migrated unmanaged disk + cpi_managed.delete_disk(disk_id) + cpi_unmanaged.delete_disk(disk_id) + @disk_id_pool.delete(disk_id) + ensure + cpi_unmanaged.delete_vm(unmanaged_instance_id) unless unmanaged_instance_id.nil? + cpi_managed.delete_vm(managed_instance_id) unless managed_instance_id.nil? end end diff --git a/src/bosh_azure_cpi/spec/integration/network/manual_network_spec.rb b/src/bosh_azure_cpi/spec/integration/network/manual_network_spec.rb index 030e2cebb..22637c7c7 100644 --- a/src/bosh_azure_cpi/spec/integration/network/manual_network_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/network/manual_network_spec.rb @@ -4,6 +4,7 @@ describe Bosh::AzureCloud::Cloud do before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") @@ -64,6 +65,7 @@ context 'with existing disks' do let!(:existing_disk_id) { @cpi.create_disk(2048, {}) } + after { @cpi.delete_disk(existing_disk_id) if existing_disk_id } it 'can excercise the vm lifecycle and list the disks' do @@ -106,7 +108,7 @@ expect do @cpi.attach_disk(new_instance_id, disk_id) - end.to_not raise_error + end.not_to raise_error expect(@cpi.get_disks(new_instance_id)).to include(disk_id) ensure diff --git a/src/bosh_azure_cpi/spec/integration/resources/additional_resource_group_spec.rb b/src/bosh_azure_cpi/spec/integration/resources/additional_resource_group_spec.rb index 15c20a26b..4af0cee57 100644 --- a/src/bosh_azure_cpi/spec/integration/resources/additional_resource_group_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/resources/additional_resource_group_spec.rb @@ -9,6 +9,7 @@ end before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") diff --git a/src/bosh_azure_cpi/spec/integration/resources/availability_sets_spec.rb b/src/bosh_azure_cpi/spec/integration/resources/availability_sets_spec.rb index 917ad60d0..692ec5550 100644 --- a/src/bosh_azure_cpi/spec/integration/resources/availability_sets_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/resources/availability_sets_spec.rb @@ -4,6 +4,7 @@ describe Bosh::AzureCloud::Cloud do before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") diff --git a/src/bosh_azure_cpi/spec/integration/resources/availability_zone_spec.rb b/src/bosh_azure_cpi/spec/integration/resources/availability_zone_spec.rb index c1b73421d..1cd6a2f6c 100644 --- a/src/bosh_azure_cpi/spec/integration/resources/availability_zone_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/resources/availability_zone_spec.rb @@ -4,6 +4,7 @@ describe Bosh::AzureCloud::Cloud do before { @disk_id_pool = [] } + after do @disk_id_pool.each do |disk_id| @logger.info("Cleanup: Deleting the disk '#{disk_id}'") diff --git a/src/bosh_azure_cpi/spec/integration/spec_helper.rb b/src/bosh_azure_cpi/spec/integration/spec_helper.rb index 54be5a170..27e2b1891 100644 --- a/src/bosh_azure_cpi/spec/integration/spec_helper.rb +++ b/src/bosh_azure_cpi/spec/integration/spec_helper.rb @@ -32,7 +32,7 @@ @subnet_name = ENV.fetch('BOSH_AZURE_SUBNET_NAME') end - rspec_config.before(:each) do + rspec_config.before do @registry = instance_double(Bosh::Cpi::RegistryClient).as_null_object allow(Bosh::Cpi::RegistryClient).to receive(:new).and_return(@registry) allow(@registry).to receive(:read_settings).and_return({}) @@ -109,4 +109,4 @@ def vm_lifecycle(stemcell_id: @stemcell_id, cpi: @cpi) def run_command(command) output, status = Open3.capture2e(command) raise "'#{command}' failed with exit status=#{status.exitstatus} [#{output}]" if status.exitstatus != 0 -end \ No newline at end of file +end diff --git a/src/bosh_azure_cpi/spec/integration/stemcell_spec.rb b/src/bosh_azure_cpi/spec/integration/stemcell_spec.rb index fa212e323..7e840a27f 100644 --- a/src/bosh_azure_cpi/spec/integration/stemcell_spec.rb +++ b/src/bosh_azure_cpi/spec/integration/stemcell_spec.rb @@ -7,7 +7,7 @@ @stemcell_path = ENV.fetch('BOSH_AZURE_STEMCELL_PATH') end - context '#stemcell' do + describe '#stemcell' do context 'with heavy stemcell', heavy_stemcell: true do let(:extract_path) { '/tmp/with-heavy-stemcell' } let(:image_path) { "#{extract_path}/image" } diff --git a/src/bosh_azure_cpi/spec/manual_tests/resource_group_name/helpers.rb b/src/bosh_azure_cpi/spec/manual_tests/resource_group_name/helpers.rb index 72df54125..2ecd83808 100755 --- a/src/bosh_azure_cpi/spec/manual_tests/resource_group_name/helpers.rb +++ b/src/bosh_azure_cpi/spec/manual_tests/resource_group_name/helpers.rb @@ -47,9 +47,7 @@ def load_bosh_azure_cpi(cpi_dir, config) cloud_config = OpenStruct.new(logger: Logger.new(STDOUT)) Bosh::Clouds::Config.configure(cloud_config) - cpi = Bosh::AzureCloud::Cloud.new(config, Bosh::AzureCloud::Cloud::CURRENT_API_VERSION) - - cpi + Bosh::AzureCloud::Cloud.new(config, Bosh::AzureCloud::Cloud::CURRENT_API_VERSION) end # return instance of cpi diff --git a/src/bosh_azure_cpi/spec/spec_helper.rb b/src/bosh_azure_cpi/spec/spec_helper.rb index f5bff9401..54fe900b9 100644 --- a/src/bosh_azure_cpi/spec/spec_helper.rb +++ b/src/bosh_azure_cpi/spec/spec_helper.rb @@ -133,11 +133,10 @@ def mock_registry_properties end def mock_registry - registry = double('registry', - endpoint: mock_registry_properties['endpoint'], - user: mock_registry_properties['user'], - password: mock_registry_properties['password']) - registry + double('registry', + endpoint: mock_registry_properties['endpoint'], + user: mock_registry_properties['user'], + password: mock_registry_properties['password']) end def mock_cloud(options = nil, api_version = 1) @@ -150,8 +149,10 @@ def time_measure Time.new - start end +# REVIEW: `run_in_new_process` is flagged as a correctable Style/ExplicitBlockArgument offense. +# However, it seems like the entire method should probably be converted into a method alias. E.g. `alias_method run_in_new_process, fork` def run_in_new_process - fork do + fork do # rubocop:todo Style/ExplicitBlockArgument yield end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb index f5f48d3e8..f246ed4f1 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/attach_disk_to_virtual_machine_spec.rb @@ -256,11 +256,11 @@ }, 'resources' => [ { - "properties": {}, - "id": 'fake-id', - "name": 'fake-name', - "type": 'fake-type', - "location": 'fake-location' + properties: {}, + id: 'fake-id', + name: 'fake-name', + type: 'fake-type', + location: 'fake-location' } ] }.to_json @@ -317,7 +317,7 @@ expect do azure_client.attach_disk_to_virtual_machine(resource_group, vm_name, disk_params) - end.to raise_error /attach_disk_to_virtual_machine - cannot find the virtual machine by name/ + end.to raise_error(/attach_disk_to_virtual_machine - cannot find the virtual machine by name/) end end @@ -360,7 +360,7 @@ expect do azure_client.attach_disk_to_virtual_machine(resource_group, vm_name, disk_params) - end.to raise_error /attach_disk_to_virtual_machine - cannot find an available lun in the virtual machine/ + end.to raise_error(/attach_disk_to_virtual_machine - cannot find an available lun in the virtual machine/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/azure_client_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/azure_client_spec.rb index 23d4f281a..2f73b06e8 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/azure_client_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/azure_client_spec.rb @@ -99,7 +99,7 @@ id = '' expect do azure_client.send(:_parse_name_from_id, id) - end.to raise_error /\"#{id}\" is not a valid URL./ + end.to raise_error(/"#{id}" is not a valid URL./) end end @@ -108,7 +108,7 @@ it 'should raise an error' do expect do azure_client.send(:_parse_name_from_id, id) - end.to raise_error /\"#{id}\" is not a valid URL./ + end.to raise_error(/"#{id}" is not a valid URL./) end end @@ -201,7 +201,7 @@ expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error /get_token - http code: 404/ + end.to raise_error(/get_token - http code: 404/) end it 'should raise an error if tenant_id, client_id or client_secret/certificate is invalid' do @@ -213,7 +213,7 @@ expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error %r{get_token - http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret\/certificate.} + end.to raise_error %r{get_token - http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret/certificate.} end it 'should raise an error if the request is invalid' do @@ -225,7 +225,7 @@ expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error %r{get_token - http code: 400. Azure authentication failed: Bad request. Please assure no typo in values of tenant_id, client_id or client_secret\/certificate.} + end.to raise_error %r{get_token - http code: 400. Azure authentication failed: Bad request. Please assure no typo in values of tenant_id, client_id or client_secret/certificate.} end it 'should raise an error if authentication retry fails' do @@ -245,7 +245,7 @@ expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error /Azure authentication failed: Token is invalid./ + end.to raise_error(/Azure authentication failed: Token is invalid./) end end @@ -298,7 +298,7 @@ it 'should raise an error' do expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error %r{get_token - http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret\/certificate.} + end.to raise_error %r{get_token - http code: 401. Azure authentication failed: Invalid tenant_id, client_id or client_secret/certificate.} end end end @@ -361,7 +361,7 @@ expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error /http_get - http code: 400. Error message: {"foo":"bar"}/ + end.to raise_error(/http_get - http code: 400. Error message: {"foo":"bar"}/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/create_public_ip_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/create_public_ip_spec.rb index 93e8892b9..117cddb70 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/create_public_ip_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/create_public_ip_spec.rb @@ -153,7 +153,7 @@ 'publicIPAllocationMethod' => 'Static' # Standard SKUs require Static }, 'zones' => ['fake-zone'], - 'sku' => {'name' => 'Standard'} + 'sku' => { 'name' => 'Standard' } } end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/create_resource_group_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/create_resource_group_spec.rb index bc1e888e4..b06768eb6 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/create_resource_group_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/create_resource_group_spec.rb @@ -110,7 +110,7 @@ ) expect do azure_client.create_resource_group(resource_group_name, location) - end.to raise_error /check_completion - http code: 200/ + end.to raise_error(/check_completion - http code: 200/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/create_storage_account_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/create_storage_account_spec.rb index 1abd9ccc4..e590e51d2 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/create_storage_account_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/create_storage_account_spec.rb @@ -183,8 +183,8 @@ headers: {} ) - expect(azure_client).to receive(:sleep).with(default_retry_after).exactly(2).times - expect(azure_client).to receive(:sleep).with(1).exactly(1).times + expect(azure_client).to receive(:sleep).with(default_retry_after).twice + expect(azure_client).to receive(:sleep).with(1).once expect( azure_client.create_storage_account(storage_account_name, location, sku, kind, tags) ).to be(true) diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/create_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/create_virtual_machine_spec.rb index eded014b4..c11d24417 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/create_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/create_virtual_machine_spec.rb @@ -1336,7 +1336,7 @@ it 'should reaise error' do expect do azure_client.create_virtual_machine(resource_group, vm_params_invalid_os_type, network_interfaces) - end.to raise_error /Unsupported os type/ + end.to raise_error(/Unsupported os type/) end end @@ -1598,6 +1598,7 @@ headers: {} ) end + it 'should not raise an error' do expect do azure_client.create_virtual_machine(resource_group, vm_params, network_interfaces) @@ -1623,7 +1624,7 @@ expect do azure_client.create_virtual_machine(resource_group, vm_params, network_interfaces) - end.to raise_error /Azure authentication failed: Token is invalid./ + end.to raise_error(/Azure authentication failed: Token is invalid./) end end end @@ -1668,7 +1669,7 @@ expect do azure_client.create_virtual_machine(resource_group, vm_params, network_interfaces) - end.to raise_error /The number of network interfaces for virtual machine xxx exceeds the maximum/ + end.to raise_error(/The number of network interfaces for virtual machine xxx exceeds the maximum/) end end @@ -1697,7 +1698,7 @@ expect do azure_client.create_virtual_machine(resource_group, vm_params, network_interfaces) - end.to raise_error /check_completion - http code: 404/ + end.to raise_error(/check_completion - http code: 404/) end it 'should raise an error if create operation failed' do @@ -1724,7 +1725,7 @@ expect do azure_client.create_virtual_machine(resource_group, vm_params, network_interfaces) - end.to raise_error { |error| expect(error.status).to eq('Cancelled') } + end.to(raise_error { |error| expect(error.status).to eq('Cancelled') }) end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/delete_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/delete_virtual_machine_spec.rb index bc2c82438..5d9809e13 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/delete_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/delete_virtual_machine_spec.rb @@ -172,7 +172,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error { |error| expect(error.status).to eq('Failed') } + end.to(raise_error { |error| expect(error.status).to eq('Failed') }) end it 'should raise an error if the body of the asynchronous response is empty' do @@ -190,7 +190,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error /The body of the asynchronous response is empty/ + end.to raise_error(/The body of the asynchronous response is empty/) end it "should raise an error if the body of the asynchronous response does not contain 'status'" do @@ -209,7 +209,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error /The body of the asynchronous response does not contain 'status'/ + end.to raise_error(/The body of the asynchronous response does not contain 'status'/) end it 'should raise an error if check completion operation is not accepeted' do @@ -228,7 +228,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error /check_completion - http code: 404/ + end.to raise_error(/check_completion - http code: 404/) end it 'should raise an error if create peration failed' do @@ -247,7 +247,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error { |error| expect(error.status).to eq('Cancelled') } + end.to(raise_error { |error| expect(error.status).to eq('Cancelled') }) end end end @@ -306,7 +306,7 @@ expect do azure_client.delete_virtual_machine(resource_group, vm_name) - end.to raise_error /Azure authentication failed: Token is invalid./ + end.to raise_error(/Azure authentication failed: Token is invalid./) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb index a19f0ba99..eb8170505 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/detach_disk_from_virtual_machine_spec.rb @@ -140,11 +140,11 @@ }, 'resources' => [ { - "properties": {}, - "id": 'fake-id', - "name": 'fake-name', - "type": 'fake-type', - "location": 'fake-location' + properties: {}, + id: 'fake-id', + name: 'fake-name', + type: 'fake-type', + location: 'fake-location' } ] }.to_json @@ -214,7 +214,7 @@ expect do azure_client.detach_disk_from_virtual_machine(resource_group, vm_name, disk_name) - end.to raise_error /detach_disk_from_virtual_machine - cannot find the virtual machine by name/ + end.to raise_error(/detach_disk_from_virtual_machine - cannot find the virtual machine by name/) end end @@ -249,7 +249,7 @@ disk_name = 'another-disk-name' expect do azure_client.detach_disk_from_virtual_machine(resource_group, vm_name, disk_name) - end.to raise_error /The disk #{disk_name} is not attached to the virtual machine #{vm_name}/ + end.to raise_error(/The disk #{disk_name} is not attached to the virtual machine #{vm_name}/) end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/get_operation_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/get_operation_spec.rb index 2c5baae7a..c6d5a0108 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/get_operation_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/get_operation_spec.rb @@ -53,8 +53,8 @@ } }, 'sku' => { - 'name' => 'Basic', - 'tier' => 'Regional' + 'name' => 'Basic', + 'tier' => 'Regional' } } end @@ -427,20 +427,20 @@ { 'value' => [ { - "name": 'Standard_A0', - "numberOfCores": 1, - "osDiskSizeInMB": 130_048, - "resourceDiskSizeInMB": 20_480, - "memoryInMB": 768, - "maxDataDiskCount": 1 + name: 'Standard_A0', + numberOfCores: 1, + osDiskSizeInMB: 130_048, + resourceDiskSizeInMB: 20_480, + memoryInMB: 768, + maxDataDiskCount: 1 }, { - "name": 'Standard_A1', - "numberOfCores": 1, - "osDiskSizeInMB": 130_048, - "resourceDiskSizeInMB": 71_680, - "memoryInMB": 1792, - "maxDataDiskCount": 2 + name: 'Standard_A1', + numberOfCores: 1, + osDiskSizeInMB: 130_048, + resourceDiskSizeInMB: 71_680, + memoryInMB: 1792, + maxDataDiskCount: 2 } ] } @@ -448,14 +448,14 @@ let(:fake_vm_size_list) do [ { - "name": 'Standard_A0', - "number_of_cores": 1, - "memory_in_mb": 768 + name: 'Standard_A0', + number_of_cores: 1, + memory_in_mb: 768 }, { - "name": 'Standard_A1', - "number_of_cores": 1, - "memory_in_mb": 1792 + name: 'Standard_A1', + number_of_cores: 1, + memory_in_mb: 1792 } ] end @@ -493,20 +493,20 @@ { 'value' => [ { - "name": 'Standard_A0', - "numberOfCores": 1, - "osDiskSizeInMB": 130_048, - "resourceDiskSizeInMB": 20_480, - "memoryInMB": 768, - "maxDataDiskCount": 1 + name: 'Standard_A0', + numberOfCores: 1, + osDiskSizeInMB: 130_048, + resourceDiskSizeInMB: 20_480, + memoryInMB: 768, + maxDataDiskCount: 1 }, { - "name": 'Standard_A1', - "numberOfCores": 1, - "osDiskSizeInMB": 130_048, - "resourceDiskSizeInMB": 71_680, - "memoryInMB": 1792, - "maxDataDiskCount": 2 + name: 'Standard_A1', + numberOfCores: 1, + osDiskSizeInMB: 130_048, + resourceDiskSizeInMB: 71_680, + memoryInMB: 1792, + maxDataDiskCount: 2 } ] } @@ -514,14 +514,14 @@ let(:fake_vm_size_list) do [ { - "name": 'Standard_A0', - "number_of_cores": 1, - "memory_in_mb": 768 + name: 'Standard_A0', + number_of_cores: 1, + memory_in_mb: 768 }, { - "name": 'Standard_A1', - "number_of_cores": 1, - "memory_in_mb": 1792 + name: 'Standard_A1', + number_of_cores: 1, + memory_in_mb: 1792 } ] end @@ -598,6 +598,7 @@ let(:fake_public_ip_list) do [fake_public_ip] end + context 'when token is valid, getting response succeeds' do it 'should return null if response body is null' do stub_request(:get, list_public_ips_uri).to_return( @@ -784,6 +785,7 @@ public_ip: fake_public_ip } end + it 'should return the network interface with public ip' do stub_request(:get, public_ip_uri).to_return( status: 200, @@ -847,6 +849,7 @@ load_balancers: [fake_load_balancer] } end + it 'should return the network interface with load balancer' do # get_load_balancer needs get_public_ip stub_request(:get, public_ip_uri).to_return( @@ -911,6 +914,7 @@ application_gateways: [fake_application_gateway] } end + it 'should return the network interface with application gateway' do stub_request(:get, application_gateway_uri).to_return( status: 200, @@ -967,6 +971,7 @@ private_ip_allocation_method: 'Dynamic' } end + it 'should return the network interface with IP forwarding enabled' do stub_request(:get, nic_uri).to_return( status: 200, @@ -1018,6 +1023,7 @@ private_ip_allocation_method: 'Dynamic' } end + it 'should return the network interface with accelerated networking enabled' do stub_request(:get, nic_uri).to_return( status: 200, @@ -1071,6 +1077,7 @@ private_ip_allocation_method: 'Dynamic' } end + it 'should return the network interface with network security group' do stub_request(:get, nsg_uri).to_return( status: 200, @@ -1129,6 +1136,7 @@ application_security_groups: [fake_asg] } end + it 'should return the network interface with public ip' do stub_request(:get, asg_uri).to_return( status: 200, @@ -1202,6 +1210,7 @@ describe '#get_storage_account_by_name' do let(:storage_account_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{default_resource_group_name}/providers/Microsoft.Storage/storageAccounts/#{storage_account_name}?api-version=#{AZURE_RESOURCE_PROVIDER_STORAGE}" } + context 'when token is valid, getting response succeeds' do context 'if response body is null' do it 'should return null' do @@ -2239,16 +2248,16 @@ let(:storage_account_list_keys_uri) { "https://management.azure.com/subscriptions/#{subscription_id}/resourceGroups/#{default_resource_group_name}/providers/Microsoft.Storage/storageAccounts/#{storage_account_name}/listKeys?api-version=#{AZURE_RESOURCE_PROVIDER_STORAGE}" } let(:storage_account_list_keys_response_body) do { - "keys": [ + keys: [ { - 'keyName': 'key1', - 'permissions': 'Full', - 'value': 'fake-key-1' + keyName: 'key1', + permissions: 'Full', + value: 'fake-key-1' }, { - 'keyName': 'key2', - 'permissions': 'Full', - 'value': 'fake-key-2' + keyName: 'key2', + permissions: 'Full', + value: 'fake-key-2' } ] }.to_json diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/get_token_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/get_token_spec.rb index cc6283c79..de5174a66 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/get_token_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/get_token_spec.rb @@ -87,19 +87,19 @@ let(:jti) { 'b55b54ac-7494-449b-94b2-d7bff0285837' } let(:header) do { - "alg": 'RS256', - "typ": 'JWT', - "x5t": x5t + alg: 'RS256', + typ: 'JWT', + x5t: x5t } end let(:payload) do { - "aud": authentication_endpoint, - "exp": (now + 3600).strftime('%s').to_i, - "iss": client_id, - "jti": jti, - "nbf": (now - 90).strftime('%s').to_i, - "sub": client_id + aud: authentication_endpoint, + exp: (now + 3600).strftime('%s').to_i, + iss: client_id, + jti: jti, + nbf: (now - 90).strftime('%s').to_i, + sub: client_id } end let(:rsa_private) { 'fake-rsa-private' } @@ -216,7 +216,7 @@ expect(azure_client).to receive(:sleep).with(30).once expect do azure_client.get_resource_by_id(url, 'api-version' => api_version) - end.to raise_error /get_token - Failed to get token/ + end.to raise_error(/get_token - Failed to get token/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/http_get_response_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/http_get_response_spec.rb index c503f2b55..b0de29488 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/http_get_response_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/http_get_response_spec.rb @@ -77,6 +77,7 @@ context 'when the response status code is one of AZURE_GENERAL_RETRY_ERROR_CODES ([408, 429, 500, 502, 503, 504])' do let(:retry_after) { 10 } + before do allow(response).to receive(:key?).with('Retry-After').and_return(true) allow(response).to receive(:[]).with('Retry-After').and_return(retry_after) diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/list_network_interfaces_by_keyword_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/list_network_interfaces_by_keyword_spec.rb index e9f3d97d9..857a193c5 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/list_network_interfaces_by_keyword_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/list_network_interfaces_by_keyword_spec.rb @@ -32,6 +32,7 @@ context 'when network interfaces are not found' do let(:result) { { 'value' => [] }.to_json } + it 'should return an empty array of network interfaces' do stub_request(:post, token_uri).to_return( status: 200, @@ -185,6 +186,7 @@ private_ip_allocation_method: 'f1' } end + it 'should return network interfaces' do stub_request(:post, token_uri).to_return( status: 200, diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/managed_disks_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/managed_disks_spec.rb index 1c584a23d..e9af83fd7 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/managed_disks_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/managed_disks_spec.rb @@ -474,6 +474,7 @@ end.not_to raise_error end end + context 'when retry reach max number.' do it 'should raise error' do stub_request(:post, token_uri).to_return( @@ -506,7 +507,7 @@ ) expect do azure_client.delete_managed_disk(resource_group, disk_name) - end.to raise_error /check_completion - http code: 200/ + end.to raise_error(/check_completion - http code: 200/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/restart_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/restart_virtual_machine_spec.rb index fb6c9db18..8e8230de9 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/restart_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/restart_virtual_machine_spec.rb @@ -143,7 +143,7 @@ expect do azure_client.restart_virtual_machine(resource_group, vm_name) - end.to raise_error /check_completion - http code: 404/ + end.to raise_error(/check_completion - http code: 404/) end it 'should raise error when internal error happens' do @@ -171,7 +171,7 @@ ) expect do azure_client.restart_virtual_machine(resource_group, vm_name) - end.to raise_error /check_completion - http code: 200/ + end.to raise_error(/check_completion - http code: 200/) end it 'should raise an error if restart operation failed' do @@ -198,7 +198,7 @@ expect do azure_client.restart_virtual_machine(resource_group, vm_name) - end.to raise_error { |error| expect(error.status).to eq('Cancelled') } + end.to(raise_error { |error| expect(error.status).to eq('Cancelled') }) end end @@ -256,7 +256,7 @@ expect do azure_client.restart_virtual_machine(resource_group, vm_name) - end.to raise_error /Azure authentication failed: Token is invalid./ + end.to raise_error(/Azure authentication failed: Token is invalid./) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_storage_account_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_storage_account_spec.rb index 76dc465be..f4b297a57 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_storage_account_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_storage_account_spec.rb @@ -88,7 +88,7 @@ expect do azure_client.update_tags_of_storage_account(storage_account_name, tags) - end.to raise_error /check_completion - http code: 200/ + end.to raise_error(/check_completion - http code: 200/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb b/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb index 02761fa00..ab0d5e92b 100644 --- a/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/azure_client/update_tags_of_virtual_machine_spec.rb @@ -53,11 +53,11 @@ }, 'resources' => [ { - "properties": {}, - "id": 'fake-id', - "name": 'fake-name', - "type": 'fake-type', - "location": 'fake-location' + properties: {}, + id: 'fake-id', + name: 'fake-name', + type: 'fake-type', + location: 'fake-location' } ] }.to_json @@ -178,11 +178,11 @@ }, 'resources' => [ { - "properties": {}, - "id": 'fake-id', - "name": 'fake-name', - "type": 'fake-type', - "location": 'fake-location' + properties: {}, + id: 'fake-id', + name: 'fake-name', + type: 'fake-type', + location: 'fake-location' } ] }.to_json @@ -253,7 +253,7 @@ expect do azure_client.update_tags_of_virtual_machine(resource_group, vm_name, tags) - end.to raise_error /update_tags_of_virtual_machine - cannot find the virtual machine by name/ + end.to raise_error(/update_tags_of_virtual_machine - cannot find the virtual machine by name/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/blob_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/blob_manager_spec.rb index 48bb4f9bb..95ff1f82b 100644 --- a/src/bosh_azure_cpi/spec/unit/blob_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/blob_manager_spec.rb @@ -48,7 +48,7 @@ .and_return(storage_account) allow(azure_storage_client).to receive(:storage_blob_host).and_return(blob_host) allow(Azure::Storage::Blob::BlobService).to receive(:new).with(client: azure_storage_client) - .and_return(blob_service) + .and_return(blob_service) allow(Bosh::AzureCloud::CustomizedRetryPolicyFilter).to receive(:new) .and_return(customized_retry) allow(blob_service).to receive(:with_filter).with(customized_retry) @@ -71,13 +71,14 @@ describe '#get_sas_blob_uri' do let(:now) { Time.new } let(:mock_sas_token) { 'mock_sas_token' } + before do allow(Time).to receive(:new).and_return(now) allow(sas_generator).to receive(:generate_service_sas_token) .with( "#{container_name}/#{blob_name}", service: 'b', resource: 'b', permissions: 'r', protocol: 'https', - expiry: (now + 3600 * 24 * 7).utc.iso8601 + expiry: (now + (3600 * 24 * 7)).utc.iso8601 ).and_return(mock_sas_token) end @@ -147,6 +148,7 @@ @file_path = '/tmp/fake_image' File.open(@file_path, 'wb') { |f| f.write('Hello CloudFoundry!') } end + after(:context) do File.delete(@file_path) if File.exist?(@file_path) end @@ -175,7 +177,7 @@ it 'should raise an error' do expect do blob_manager.create_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, @file_path, blob_name, metadata) - end.to raise_error /Failed to upload page blob/ + end.to raise_error(/Failed to upload page blob/) end end @@ -191,7 +193,7 @@ expect(blob_service).to receive(:delete_blob) expect do blob_manager.create_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, @file_path, blob_name, metadata) - end.to raise_error /put blob pages failed/ + end.to raise_error(/put blob pages failed/) end end end @@ -203,9 +205,11 @@ @empty_chunk_content = Array.new(MAX_CHUNK_SIZE, 0).pack('c*') File.open(@empty_file_path, 'wb') { |f| f.write(@empty_chunk_content) } end + after do File.delete(@empty_file_path) if File.exist?(@empty_file_path) end + it 'should not call put_blob_pages' do expect(blob_service).to receive(:create_page_blob) .with(container_name, blob_name, kind_of(Numeric), options) @@ -250,7 +254,7 @@ it 'should raise an error' do expect do blob_manager.create_empty_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, blob_name, 1, metadata) - end.to raise_error /Failed to create empty page blob/ + end.to raise_error(/Failed to create empty page blob/) end end @@ -260,6 +264,7 @@ request_id: request_id } end + before do times = 0 allow(blob_service).to receive(:create_page_blob) do @@ -324,7 +329,7 @@ expect do blob_manager.create_empty_vhd_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, blob_name, 1024) - end.to raise_error /Failed to create empty vhd blob/ + end.to raise_error(/Failed to create empty vhd blob/) end end @@ -339,7 +344,7 @@ expect do blob_manager.create_empty_vhd_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, blob_name, 1024) - end.to raise_error /Failed to create empty vhd blob/ + end.to raise_error(/Failed to create empty vhd blob/) end end end @@ -351,14 +356,17 @@ @empty_chunk_content = Array.new(2 * 1024 * 1024, 0).pack('c*') File.open(@file_path, 'wb') { |f| f.write(@empty_chunk_content) } end + after(:context) do File.delete(@file_path) if File.exist?(@file_path) end + context 'when creating vhd page blob succeeds' do before do allow(blob_service).to receive(:create_page_blob) allow(blob_service).to receive(:put_blob_pages) end + it 'raise no error' do expect do blob_manager.create_vhd_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, @file_path, blob_name, metadata) @@ -372,22 +380,25 @@ allow(blob_service).to receive(:create_page_blob) allow(blob_service).to receive(:put_blob_pages).and_raise(StandardError) end + it 'page blob should be deleted' do expect(blob_service).to receive(:delete_blob) expect do blob_manager.create_vhd_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, @file_path, blob_name, metadata) - end.to raise_error /Failed to upload page blob/ + end.to raise_error(/Failed to upload page blob/) end end + context 'page blob not created' do before do allow(blob_service).to receive(:create_page_blob).and_raise(StandardError) end + it 'page blob should be deleted' do expect(blob_service).not_to receive(:delete_blob) expect do blob_manager.create_vhd_page_blob(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, @file_path, blob_name, metadata) - end.to raise_error /Failed to upload page blob/ + end.to raise_error(/Failed to upload page blob/) end end end @@ -506,10 +517,11 @@ allow(blob_service).to receive(:set_blob_metadata) .and_raise('(404)') end + it 'should raise error' do expect do blob_manager.set_blob_metadata(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name, blob_name, metadata) - end.to raise_error /(404)/ + end.to raise_error(/(404)/) end end end @@ -523,7 +535,7 @@ it 'should return empty' do expect do blob_manager.list_blobs(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, container_name) - end.to raise_error /The container does not exist/ + end.to raise_error(/The container does not exist/) end end @@ -622,6 +634,7 @@ } end let(:blob) { instance_double(Azure::Storage::Blob::Blob) } + before do allow(azure_client).to receive(:get_storage_account_by_name) .with(another_storage_account_name) @@ -675,6 +688,7 @@ copy_progress: '5678/5678' } end + before do allow_any_instance_of(Object).to receive(:sleep).and_return(nil) allow(blob_service).to receive(:copy_blob_from_uri).and_return(['fake-copy-id', 'pending']) @@ -695,6 +709,7 @@ request_id: request_id } end + before do times = 0 allow(blob_service).to receive(:copy_blob_from_uri) do @@ -745,7 +760,7 @@ expect do blob_manager.copy_blob(another_storage_account_name, container_name, blob_name, source_blob_uri) - end.to raise_error /Failed to copy the blob/ + end.to raise_error(/Failed to copy the blob/) end end @@ -765,6 +780,7 @@ copy_status_description: 'fake-status-description' } end + before do allow_any_instance_of(Object).to receive(:sleep).and_return(nil) allow(blob_service).to receive(:copy_blob_from_uri).and_return(['fake-copy-id', 'pending']) @@ -777,7 +793,7 @@ expect do blob_manager.copy_blob(another_storage_account_name, container_name, blob_name, source_blob_uri) - end.to raise_error /Failed to copy the blob/ + end.to raise_error(/Failed to copy the blob/) end end end @@ -790,6 +806,7 @@ copy_status: 'interrupted' } end + before do allow_any_instance_of(Object).to receive(:sleep).and_return(nil) allow(blob_service).to receive(:copy_blob_from_uri).and_return(['fake-copy-id', 'pending']) @@ -802,7 +819,7 @@ expect do blob_manager.copy_blob(another_storage_account_name, container_name, blob_name, source_blob_uri) - end.to raise_error %r{The progress of copying the blob #{source_blob_uri} to #{container_name}\/#{blob_name} was interrupted} + end.to raise_error %r{The progress of copying the blob #{source_blob_uri} to #{container_name}/#{blob_name} was interrupted} end end @@ -815,6 +832,7 @@ copy_progress: '1234/5678' } end + before do allow(blob_service).to receive(:copy_blob_from_uri).and_return(['fake-copy-id', 'pending']) allow(blob).to receive(:properties).and_return(blob_properties) @@ -826,7 +844,7 @@ expect do blob_manager.copy_blob(another_storage_account_name, container_name, blob_name, source_blob_uri) - end.to raise_error %r{The progress of copying the blob #{source_blob_uri} to #{container_name}\/#{blob_name} was interrupted} + end.to raise_error %r{The progress of copying the blob #{source_blob_uri} to #{container_name}/#{blob_name} was interrupted} end end end @@ -835,10 +853,11 @@ before do allow(blob_service).to receive(:copy_blob_from_uri).and_raise('Unexpected Error') end + it 'succeeds to copy the blob' do expect do blob_manager.copy_blob(another_storage_account_name, container_name, blob_name, source_blob_uri) - end.to raise_error /Unexpected Error/ + end.to raise_error(/Unexpected Error/) end end end @@ -846,6 +865,7 @@ describe Bosh::AzureCloud::CustomizedRetryPolicyFilter do let(:customized_retry_policy_filter) { Bosh::AzureCloud::CustomizedRetryPolicyFilter.new } + describe '#apply_retry_policy' do context 'when there is no error' do let(:retry_data) { {} } diff --git a/src/bosh_azure_cpi/spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb b/src/bosh_azure_cpi/spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb index 8f3cca39d..cde208017 100644 --- a/src/bosh_azure_cpi/spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/bosh_release/jobs/cpi/templates/cpi.json.erb_spec.rb @@ -613,7 +613,7 @@ def initialize(spec, manifest) def recursive_merge(hash, other) hash.merge(other) do |_, old_value, new_value| - if old_value.class == Hash && new_value.class == Hash + if old_value.instance_of?(Hash) && new_value.instance_of?(Hash) recursive_merge(old_value, new_value) else new_value @@ -643,7 +643,7 @@ def if_p(*names) value end - yield *values + yield(*values) InactiveElseBlock.new end diff --git a/src/bosh_azure_cpi/spec/unit/cloud/attach_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/attach_disk_spec.rb index 9411cf785..736252f9d 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/attach_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/attach_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -69,6 +69,7 @@ context 'when use_managed_disks is true' do context 'when the disk is a managed disk' do let(:disk) { {} } + before do allow(disk_manager2).to receive(:get_data_disk).with(disk_id_object).and_return(disk) end @@ -124,9 +125,10 @@ it "can't attach a managed disk to a VM with unmanaged disks" do expect do managed_cloud.attach_disk(vm_cid, disk_cid) - end.to raise_error /Cannot attach a managed disk to a VM with unmanaged disks/ + end.to raise_error(/Cannot attach a managed disk to a VM with unmanaged disks/) end end + context 'when the managed disk does not exist' do before do allow(instance_id_object).to receive(:use_managed_disks?) @@ -184,7 +186,7 @@ it 'raise an error' do expect do managed_cloud.attach_disk(vm_cid, disk_cid) - end.to raise_error /attach_disk - Failed to migrate disk/ + end.to raise_error(/attach_disk - Failed to migrate disk/) end end end @@ -259,7 +261,7 @@ expect do managed_cloud.attach_disk(vm_cid, disk_cid) - end.to raise_error /attach_disk - Failed to create the managed disk/ + end.to raise_error(/attach_disk - Failed to create the managed disk/) end end @@ -273,7 +275,7 @@ expect do managed_cloud.attach_disk(vm_cid, disk_cid) - end.to raise_error /attach_disk - Failed to create the managed disk/ + end.to raise_error(/attach_disk - Failed to create the managed disk/) end end end @@ -342,25 +344,25 @@ context 'when api version is 2' do before do allow(vm_manager).to receive(:attach_disk).with(instance_id_object, disk_id_object) - .and_return(lun) + .and_return(lun) end it 'returns the disk hints' do expect(registry_client).to receive(:read_settings).with(vm_cid) - .and_return(old_settings) + .and_return(old_settings) expect(registry_client).to receive(:update_settings) - .with(vm_cid, new_settings).and_return(true) + .with(vm_cid, new_settings).and_return(true) result = cloud_v2.attach_disk(vm_cid, disk_cid) - expect(result).to eq({'lun' => lun, 'host_device_id' => host_device_id}) + expect(result).to eq({ 'lun' => lun, 'host_device_id' => host_device_id }) end context 'when stemcell api version is 2' do it 'should not write to the registry' do - expect(registry_client).to_not receive(:read_settings) - expect(registry_client).to_not receive(:update_settings) + expect(registry_client).not_to receive(:read_settings) + expect(registry_client).not_to receive(:update_settings) - expect(cloud_sc_v2.attach_disk(vm_cid, disk_cid)).to_not be_nil + expect(cloud_sc_v2.attach_disk(vm_cid, disk_cid)).not_to be_nil end end end diff --git a/src/bosh_azure_cpi/spec/unit/cloud/calculate_vm_cloud_properties_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/calculate_vm_cloud_properties_spec.rb index d23aac8a9..7fca81868 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/calculate_vm_cloud_properties_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/calculate_vm_cloud_properties_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -52,6 +52,7 @@ 'ephemeral_disk_size' => size_in_gb * 1024 } end + it 'should return the cloud_properties' do expect(azure_client).to receive(:list_available_virtual_machine_sizes_by_location).with(location).and_return(available_vm_sizes) expect(instance_type_mapper).to receive(:map) @@ -71,9 +72,10 @@ { 'cpu' => 1, 'ram' => 1024, - 'ephemeral_disk_size' => size_in_gb * 1024 + 1 + 'ephemeral_disk_size' => (size_in_gb * 1024) + 1 } end + it 'should return the cloud_properties' do expect(azure_client).to receive(:list_available_virtual_machine_sizes_by_location).with(location).and_return(available_vm_sizes) expect(instance_type_mapper).to receive(:map) diff --git a/src/bosh_azure_cpi/spec/unit/cloud/cloud_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/cloud_spec.rb index b3f289af1..d9c0420c8 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/cloud_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/cloud_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -17,7 +17,7 @@ it 'raises an exception with a user friendly message' do expect(FileUtils).to receive(:mkdir_p).with(CPI_LOCK_DIR).and_call_original expect do - cloud.has_vm?("fake-vm-cid") + cloud.has_vm?('fake-vm-cid') end.to raise_error(Bosh::Clouds::CloudError, 'Please make sure the CPI has proper network access to Azure. #') end end diff --git a/src/bosh_azure_cpi/spec/unit/cloud/configure_networks_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/configure_networks_spec.rb index 0f32468b5..c7b031da7 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/configure_networks_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/configure_networks_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/create_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/create_disk_spec.rb index 9a6010b10..51352fe25 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/create_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/create_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -47,7 +47,7 @@ it 'should raise an error' do expect do cloud.create_disk(disk_size, cloud_properties, vm_cid) - end.to raise_error /Azure CPI minimum disk size is 1 GiB/ + end.to raise_error(/Azure CPI minimum disk size is 1 GiB/) end end end @@ -64,7 +64,7 @@ it 'should raise an error' do expect do cloud.create_disk(disk_size, cloud_properties, vm_cid) - end.to raise_error /Unknown disk caching/ + end.to raise_error(/Unknown disk caching/) end end end @@ -119,7 +119,7 @@ it "can't create a managed disk for a VM with unmanaged disks" do expect do managed_cloud.create_disk(disk_size, cloud_properties, vm_cid) - end.to raise_error /Cannot create a managed disk for a VM with unmanaged disks/ + end.to raise_error(/Cannot create a managed disk for a VM with unmanaged disks/) end end @@ -163,6 +163,7 @@ 'storage_account_type' => 'Standard_LRS' } end + it 'should create a managed disk in the same location with the vm and use the specified storage account type' do expect(Bosh::AzureCloud::DiskId).to receive(:create) .with(caching, true, resource_group_name: resource_group_name) diff --git a/src/bosh_azure_cpi/spec/unit/cloud/create_stemcell_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/create_stemcell_spec.rb index 83b20fec6..507c9f001 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/create_stemcell_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/create_stemcell_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/create_vm_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/create_vm_spec.rb index 68790fb4b..1052720d4 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/create_vm_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/create_vm_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -117,6 +117,7 @@ } } end + before do allow(vm_manager).to receive(:get_storage_account_from_vm_properties) .with(vm_props, location) @@ -158,6 +159,7 @@ context 'when the location in the global configuration is different from the vnet location' do let(:cloud_properties_with_location) { mock_cloud_properties_merge('azure' => { 'location' => "location-other-than-#{location}" }) } let(:cloud_with_location) { mock_cloud(cloud_properties_with_location) } + before do allow(Bosh::AzureCloud::NetworkConfigurator).to receive(:new) .with(cloud_with_location.config.azure, networks) @@ -410,30 +412,30 @@ before do allow(Bosh::AzureCloud::BoshVMMeta).to receive(:new) - .with(agent_id, stemcell_cid) - .and_return(bosh_vm_meta) + .with(agent_id, stemcell_cid) + .and_return(bosh_vm_meta) allow(instance_id).to receive(:to_s) - .and_return(instance_id_string) + .and_return(instance_id_string) allow(Bosh::AzureCloud::NetworkConfigurator).to receive(:new) - .with(anything, networks) - .and_return(network_configurator) + .with(anything, networks) + .and_return(network_configurator) end it 'returns an array of instance id and networks' do expect(registry_client).to receive(:update_settings) expect(vm_manager).to receive(:create) - .with(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, environment, agent_util, networks, cloud_v2.config) - .and_return([instance_id_string, {}]) + .with(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, environment, agent_util, networks, cloud_v2.config) + .and_return([instance_id_string, {}]) expect( - cloud_v2.create_vm( - agent_id, - stemcell_cid, - cloud_properties, - networks, - disk_cids, - environment - ) + cloud_v2.create_vm( + agent_id, + stemcell_cid, + cloud_properties, + networks, + disk_cids, + environment + ) ).to eq([instance_id_string, networks]) end @@ -443,29 +445,29 @@ expect(vm_manager).to receive(:create) cloud_v2.create_vm( - agent_id, - stemcell_cid, - cloud_properties, - networks, - disk_cids, - environment + agent_id, + stemcell_cid, + cloud_properties, + networks, + disk_cids, + environment ) end context 'and stemcell api version is 2' do it 'does not write to the registry' do - expect(registry_client).to_not receive(:update_settings) + expect(registry_client).not_to receive(:update_settings) expect(vm_manager).to receive(:create).and_return([instance_id_string, networks]) expect( - cloud_sc_v2.create_vm( - agent_id, - stemcell_cid, - cloud_properties, - networks, - disk_cids, - environment - ) + cloud_sc_v2.create_vm( + agent_id, + stemcell_cid, + cloud_properties, + networks, + disk_cids, + environment + ) ).to eq([instance_id_string, networks]) end end diff --git a/src/bosh_azure_cpi/spec/unit/cloud/current_vm_id_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/current_vm_id_spec.rb index ac863fbcb..6bc119220 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/current_vm_id_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/current_vm_id_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/delete_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/delete_disk_spec.rb index 9afe10387..e2bbf347e 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/delete_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/delete_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/delete_snapshot_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/delete_snapshot_spec.rb index 2badf5e02..3c6a5f52c 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/delete_snapshot_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/delete_snapshot_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -9,6 +9,7 @@ describe '#delete_snapshot' do let(:snapshot_cid) { 'fake-snapshot-cid' } let(:snapshot_id_object) { instance_double(Bosh::AzureCloud::DiskId) } + before do allow(telemetry_manager).to receive(:monitor) .with('delete_snapshot', id: snapshot_cid).and_call_original diff --git a/src/bosh_azure_cpi/spec/unit/cloud/delete_stemcell_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/delete_stemcell_spec.rb index 4e6724e86..a9643ac7f 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/delete_stemcell_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/delete_stemcell_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/delete_vm_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/delete_vm_spec.rb index d05accf56..2407ad056 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/delete_vm_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/delete_vm_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/detach_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/detach_disk_spec.rb index cb53ad77d..7a5026197 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/detach_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/detach_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/get_disks_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/get_disks_spec.rb index d39372745..cccaad84b 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/get_disks_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/get_disks_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/has_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/has_disk_spec.rb index bab24c648..3a9d119f3 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/has_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/has_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/has_vm_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/has_vm_spec.rb index 49719f38c..99fc2a40d 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/has_vm_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/has_vm_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/info_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/info_spec.rb index bd04d1302..83c1bf855 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/info_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/info_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/reboot_vm_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/reboot_vm_spec.rb index a66419492..670ef31c0 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/reboot_vm_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/reboot_vm_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/resize_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/resize_disk_spec.rb index 018f4a5ab..1b31d27f0 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/resize_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/resize_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/set_disk_metadata_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/set_disk_metadata_spec.rb index fd3432f82..2f13ef80c 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/set_disk_metadata_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/set_disk_metadata_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' @@ -13,9 +13,7 @@ it 'should raise a NotSupported error' do expect do cloud.set_disk_metadata(disk_cid, metadata) - end.to raise_error { - Bosh::Clouds::NotSupported - } + end.to raise_error(Bosh::Clouds::NotImplemented) end end end diff --git a/src/bosh_azure_cpi/spec/unit/cloud/set_vm_metadata_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/set_vm_metadata_spec.rb index 1054412bb..a2f58a36e 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/set_vm_metadata_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/set_vm_metadata_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/cloud/shared_stuff.rb b/src/bosh_azure_cpi/spec/unit/cloud/shared_stuff.rb index df6ef2752..44c28de13 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/shared_stuff.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/shared_stuff.rb @@ -19,7 +19,7 @@ let(:instance_type_mapper) { instance_double('Bosh::AzureCloud::InstanceTypeMapper') } let(:telemetry_manager) { MockTelemetryManager.new } let(:cloud_v2) { mock_cloud(nil, 2) } - let(:cloud_sc_v2) { mock_cloud(mock_cloud_properties_merge('azure' => {'vm' => {'stemcell' => {'api_version' => 2}}}), 2) } + let(:cloud_sc_v2) { mock_cloud(mock_cloud_properties_merge('azure' => { 'vm' => { 'stemcell' => { 'api_version' => 2 } } }), 2) } before do allow(Bosh::Cpi::RegistryClient).to receive(:new) diff --git a/src/bosh_azure_cpi/spec/unit/cloud/snapshot_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/cloud/snapshot_disk_spec.rb index 0f8ab1b23..87ddeffbb 100644 --- a/src/bosh_azure_cpi/spec/unit/cloud/snapshot_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/cloud/snapshot_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::Cloud do include_context 'shared stuff' diff --git a/src/bosh_azure_cpi/spec/unit/disk_id_spec.rb b/src/bosh_azure_cpi/spec/unit/disk_id_spec.rb index 565bd2724..e5eda58a2 100644 --- a/src/bosh_azure_cpi/spec/unit/disk_id_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/disk_id_spec.rb @@ -41,6 +41,7 @@ context 'when use_managed_disks is false' do let(:use_managed_disks) { false } + it 'should generate a disk name with prefix bosh-data' do disk_id = Bosh::AzureCloud::DiskId.create(caching, use_managed_disks, disk_name: nil, storage_account_name: storage_account_name) expect(disk_id.disk_name).to start_with('bosh-data') @@ -278,7 +279,7 @@ it 'should raise an error' do expect do disk_id.caching - end.to raise_error /This function should only be called for data disks/ + end.to raise_error(/This function should only be called for data disks/) end end end @@ -288,11 +289,12 @@ let(:caching) { 'None' } let(:storage_account_name) { 'fake-storage-account-name' } let(:disk_id_string) { "wrongbosh-data-#{storage_account_name}-#{SecureRandom.uuid}-#{caching}" } + it 'should raise error' do expect do disk_id = Bosh::AzureCloud::DiskId.parse(disk_id_string, 'fake-resource-group-name') disk_id.storage_account_name - end.to raise_error /Invalid data disk name/ + end.to raise_error(/Invalid data disk name/) end end @@ -324,7 +326,7 @@ it 'should raise an error' do expect do disk_id.storage_account_name - end.to raise_error /This function should only be called for unmanaged disks/ + end.to raise_error(/This function should only be called for unmanaged disks/) end end end @@ -337,7 +339,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid disk_name in disk id \(version 2\)/ + end.to raise_error(/Invalid disk_name in disk id \(version 2\)/) end end end @@ -349,7 +351,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid caching in disk id \(version 2\)/ + end.to raise_error(/Invalid caching in disk id \(version 2\)/) end end @@ -359,7 +361,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid caching in disk id \(version 2\)/ + end.to raise_error(/Invalid caching in disk id \(version 2\)/) end end end @@ -371,7 +373,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid resource_group_name in disk id \(version 2\)/ + end.to raise_error(/Invalid resource_group_name in disk id \(version 2\)/) end end end @@ -383,7 +385,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid storage_account_name in disk id \(version 2\)/ + end.to raise_error(/Invalid storage_account_name in disk id \(version 2\)/) end end @@ -393,7 +395,7 @@ it 'should raise an error' do expect do disk_id.validate - end.to raise_error /Invalid storage_account_name in disk id \(version 2\)/ + end.to raise_error(/Invalid storage_account_name in disk id \(version 2\)/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/disk_manager2_spec.rb b/src/bosh_azure_cpi/spec/unit/disk_manager2_spec.rb index 77f72c4d4..dbf03ebd2 100644 --- a/src/bosh_azure_cpi/spec/unit/disk_manager2_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/disk_manager2_spec.rb @@ -174,6 +174,7 @@ .with(resource_group_name, disk_name) .and_return({}) end + it 'should return true' do expect(disk_manager2.has_data_disk?(disk_id)).to be(true) end @@ -185,6 +186,7 @@ .with(resource_group_name, disk_name) .and_return(nil) end + it 'should return false' do expect(disk_manager2.has_data_disk?(disk_id)).to be(false) end @@ -193,6 +195,7 @@ describe '#get_data_disk' do let(:mock_disk) { {} } + it 'should get the disk' do expect do expect(azure_client).to receive(:get_managed_disk_by_name) @@ -343,7 +346,7 @@ it 'should raise an error' do expect do disk_manager2.os_disk(vm_name, stemcell_info, vm_props.root_disk.size, vm_props.caching, vm_props.ephemeral_disk.use_root_disk) - end.to raise_error /Unknown disk caching/ + end.to raise_error(/Unknown disk caching/) end end end @@ -401,8 +404,10 @@ context 'when the OS is Linux' do let(:minimum_required_disk_size) { 30 } + context 'when the image_size is smaller than the minimum required disk size' do let(:image_size) { (minimum_required_disk_size - 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -421,6 +426,7 @@ context 'when the image_size is larger than minimum required disk size' do let(:image_size) { (minimum_required_disk_size + 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -440,6 +446,7 @@ context 'when the OS is Windows' do let(:minimum_required_disk_size) { 128 } + before do allow(stemcell_info).to receive(:is_windows?) .and_return(true) @@ -447,6 +454,7 @@ context 'when the image_size is smaller than the minimum required disk size' do let(:image_size) { (minimum_required_disk_size - 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -465,6 +473,7 @@ context 'when the image_size is larger than minimum required disk size' do let(:image_size) { (minimum_required_disk_size + 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -512,6 +521,7 @@ ) end let(:image_size) { 4 * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -554,7 +564,7 @@ props_factory.parse_vm_props( 'instance_type' => 'STANDARD_A1', 'root_disk' => { - 'size' => 5 * 1024 + 512 + 'size' => (5 * 1024) + 512 } ) end @@ -802,7 +812,7 @@ it 'should raise an error' do expect do disk_manager2.migrate_to_zone(disk_id, disk, zone) - end.to raise_error /migrate_to_zone - Can'n find snapshot '#{snapshot_name}' in resource group '#{resource_group_name}'/ + end.to raise_error(/migrate_to_zone - Can'n find snapshot '#{snapshot_name}' in resource group '#{resource_group_name}'/) end end @@ -818,7 +828,7 @@ expect do disk_manager2.migrate_to_zone(disk_id, disk, zone) - end.to raise_error /fails to create disk/ + end.to raise_error(/fails to create disk/) end end @@ -831,7 +841,7 @@ count == 1 ? raise('fails to create disk') : nil end - expect(azure_client).to receive(:create_managed_disk_from_snapshot).exactly(2).times + expect(azure_client).to receive(:create_managed_disk_from_snapshot).twice expect do disk_manager2.migrate_to_zone(disk_id, disk, zone) @@ -851,7 +861,7 @@ expect do disk_manager2.migrate_to_zone(disk_id, disk, zone) - end.to raise_error /migrate_to_zone - Can'n find disk '#{disk_name}' in resource group '#{resource_group_name}' after migration/ + end.to raise_error(/migrate_to_zone - Can'n find disk '#{disk_name}' in resource group '#{resource_group_name}' after migration/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/disk_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/disk_manager_spec.rb index 809c7d909..a09dbfc3e 100644 --- a/src/bosh_azure_cpi/spec/unit/disk_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/disk_manager_spec.rb @@ -154,7 +154,7 @@ it 'should raise an error' do expect do disk_manager.delete_snapshot(snapshot_id) - end.to raise_error /Invalid snapshot id/ + end.to raise_error(/Invalid snapshot id/) end end @@ -197,6 +197,7 @@ allow(blob_manager).to receive(:get_blob_properties) .and_return({}) end + it 'should delete the disk' do expect(disk_manager.has_data_disk?(disk_id)).to be(true) end @@ -228,6 +229,7 @@ 'migrated' => 'true' } end + before do allow(blob_manager).to receive(:get_blob_metadata) .and_return(metadata) @@ -240,6 +242,7 @@ context "when the disk doesn't have the metadata" do let(:metadata) { {} } + before do allow(blob_manager).to receive(:get_blob_metadata) .and_return(metadata) @@ -372,7 +375,7 @@ it 'should raise an error' do expect do disk_manager.os_disk(storage_account_name, vm_name, stemcell_info, vm_props.root_disk.size, vm_props.caching, vm_props.ephemeral_disk.use_root_disk) - end.to raise_error /Unknown disk caching/ + end.to raise_error(/Unknown disk caching/) end end end @@ -432,8 +435,10 @@ context 'when the OS is Linux' do let(:minimum_required_disk_size) { 30 } + context 'when the image_size is smaller than minimum required disk size' do let(:image_size) { (minimum_required_disk_size - 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -453,6 +458,7 @@ context 'when the image_size is larger than minimum required disk size' do let(:image_size) { (minimum_required_disk_size + 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -473,6 +479,7 @@ context 'when the OS is Windows' do let(:minimum_required_disk_size) { 128 } + before do allow(stemcell_info).to receive(:is_windows?) .and_return(true) @@ -480,6 +487,7 @@ context 'when the image_size is smaller than minimum required disk size' do let(:image_size) { (minimum_required_disk_size - 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -499,6 +507,7 @@ context 'when the image_size is larger than minimum required disk size' do let(:image_size) { (minimum_required_disk_size + 1) * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -547,6 +556,7 @@ ) end let(:image_size) { 4 * 1024 } + before do allow(stemcell_info).to receive(:image_size) .and_return(image_size) @@ -591,7 +601,7 @@ props_factory.parse_vm_props( 'instance_type' => 'STANDARD_A1', 'root_disk' => { - 'size' => 5 * 1024 + 512 + 'size' => (5 * 1024) + 512 } ) end diff --git a/src/bosh_azure_cpi/spec/unit/helpers_spec.rb b/src/bosh_azure_cpi/spec/unit/helpers_spec.rb index e66195336..fbfffd595 100644 --- a/src/bosh_azure_cpi/spec/unit/helpers_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/helpers_spec.rb @@ -32,6 +32,7 @@ def set_logger(logger) context 'when logger is not nil' do let(:logger_strio) { StringIO.new } + before do helpers_tester.set_logger(Logger.new(logger_strio)) end @@ -47,6 +48,7 @@ def set_logger(logger) context 'when exception is not nil' do let(:fake_exception) { StandardError.new('fake-exception') } + it 'should raise CloudError, log the message and the exception' do expect do helpers_tester.cloud_error(message, fake_exception) @@ -95,7 +97,7 @@ def set_logger(logger) it 'should raise an error' do expect do helpers_tester.validate_disk_caching(caching) - end.to raise_error /Unknown disk caching/ + end.to raise_error(/Unknown disk caching/) end end end @@ -105,7 +107,7 @@ def set_logger(logger) it 'should ignore any exception' do expect do helpers_tester.ignore_exception do - raise Exception + raise Exception # rubocop:disable Lint/RaiseException end end.not_to raise_error end @@ -130,6 +132,7 @@ def set_logger(logger) describe '#bosh_jobs_dir' do context 'when the environment variable BOSH_JOBS_DIR exists' do let(:bosh_jobs_dir) { '.bosh_init/installations/a3ee66ec-6f00-4aab-632d-f6d4c5dc5f5b/jobs' } + before do allow(ENV).to receive(:[]).with('BOSH_JOBS_DIR').and_return(bosh_jobs_dir) end @@ -400,6 +403,7 @@ def set_logger(logger) describe '#get_service_principal_certificate_path' do context 'when the environment variable BOSH_JOBS_DIR exists' do let(:bosh_jobs_dir) { '.bosh_init/installations/a3ee66ec-6f00-4aab-632d-f6d4c5dc5f5b/jobs' } + before do allow(ENV).to receive(:[]).with('BOSH_JOBS_DIR').and_return(bosh_jobs_dir) end @@ -427,19 +431,19 @@ def set_logger(logger) let(:jti) { 'b55b54ac-7494-449b-94b2-d7bff0285837' } let(:header) do { - "alg": 'RS256', - "typ": 'JWT', - "x5t": x5t + alg: 'RS256', + typ: 'JWT', + x5t: x5t } end let(:payload) do { - "aud": authentication_endpoint, - "exp": (now + 3600).strftime('%s').to_i, - "iss": client_id, - "jti": jti, - "nbf": (now - 90).strftime('%s').to_i, - "sub": client_id + aud: authentication_endpoint, + exp: (now + 3600).strftime('%s').to_i, + iss: client_id, + jti: jti, + nbf: (now - 90).strftime('%s').to_i, + sub: client_id } end let(:rsa_private) { 'fake-rsa-private' } @@ -465,7 +469,7 @@ def set_logger(logger) expect(JWT).to receive(:encode).with(payload, rsa_private, 'RS256', header).and_raise('JWT-ENCODING-ERROR') expect do helpers_tester.get_jwt_assertion(authentication_endpoint, client_id) - end.to raise_error /Failed to get the jwt assertion: .*JWT-ENCODING-ERROR/ + end.to raise_error(/Failed to get the jwt assertion: .*JWT-ENCODING-ERROR/) end end end @@ -500,7 +504,7 @@ def set_logger(logger) it 'should create the storage client with the correct options' do expect(Azure::Storage::Common::Client).to receive(:create).with(options) - .and_return(azure_storage_client) + .and_return(azure_storage_client) expect( helpers_tester.initialize_azure_storage_client(storage_account, azure_config) ).to eq(azure_storage_client) @@ -529,7 +533,7 @@ def set_logger(logger) it 'should create the storage client with the correct options' do expect(Azure::Storage::Common::Client).to receive(:create).with(options) - .and_return(azure_storage_client) + .and_return(azure_storage_client) expect( helpers_tester.initialize_azure_storage_client(storage_account, azure_config) ).to eq(azure_storage_client) @@ -540,6 +544,7 @@ def set_logger(logger) describe '#get_ca_cert_path' do context 'when the environment variable BOSH_JOBS_DIR exists' do let(:bosh_jobs_dir) { '.bosh_init/installations/a3ee66ec-6f00-4aab-632d-f6d4c5dc5f5b/jobs' } + before do allow(ENV).to receive(:[]).with('BOSH_JOBS_DIR').and_return(bosh_jobs_dir) end @@ -835,6 +840,7 @@ def set_logger(logger) context 'when metadata is empty' do let(:uri) { 'fake-uri' } let(:metadata) { {} } + it 'should return correct values' do stemcell_info = Bosh::AzureCloud::Helpers::StemcellInfo.new(uri, metadata) expect(stemcell_info.uri).to eq('fake-uri') @@ -893,8 +899,10 @@ def set_logger(logger) context 'for single process' do let(:mode) { File::LOCK_EX } + context 'when the block is executed successfully' do let(:result) { 'fake-result' } + it 'should return the result' do expect(File).to receive(:open).and_call_original expect_any_instance_of(File).to receive(:flock).with(mode).and_call_original diff --git a/src/bosh_azure_cpi/spec/unit/instance_id_spec.rb b/src/bosh_azure_cpi/spec/unit/instance_id_spec.rb index 921c3266e..8bfb59a25 100644 --- a/src/bosh_azure_cpi/spec/unit/instance_id_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/instance_id_spec.rb @@ -251,7 +251,7 @@ it 'should raise an error' do expect do Bosh::AzureCloud::InstanceId.parse(instance_id_string, 'fake-resource-group-name') - end.to raise_error /Invalid instance id \(plain\)/ + end.to raise_error(/Invalid instance id \(plain\)/) end end @@ -261,7 +261,7 @@ it 'should raise an error' do expect do Bosh::AzureCloud::InstanceId.parse(instance_id_string, 'fake-resource-group-name') - end.to raise_error /Invalid instance id \(plain\)/ + end.to raise_error(/Invalid instance id \(plain\)/) end end end @@ -274,7 +274,7 @@ it 'should raise an error' do expect do instance_id.validate - end.to raise_error /Invalid resource_group_name in instance id \(version 2\)/ + end.to raise_error(/Invalid resource_group_name in instance id \(version 2\)/) end end @@ -284,7 +284,7 @@ it 'should raise an error' do expect do instance_id.validate - end.to raise_error /Invalid resource_group_name in instance id \(version 2\)/ + end.to raise_error(/Invalid resource_group_name in instance id \(version 2\)/) end end end @@ -296,7 +296,7 @@ it 'should raise an error' do expect do instance_id.validate - end.to raise_error /Invalid vm_name in instance id \(version 2\)/ + end.to raise_error(/Invalid vm_name in instance id \(version 2\)/) end end @@ -306,7 +306,7 @@ it 'should raise an error' do expect do instance_id.validate - end.to raise_error /Invalid vm_name in instance id \(version 2\)/ + end.to raise_error(/Invalid vm_name in instance id \(version 2\)/) end end end @@ -318,7 +318,7 @@ it 'should raise an error' do expect do instance_id.validate - end.to raise_error /Invalid storage_account_name in instance id \(version 2\)/ + end.to raise_error(/Invalid storage_account_name in instance id \(version 2\)/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/light_stemcell_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/light_stemcell_manager_spec.rb index 64b08a1de..e42e06e5f 100644 --- a/src/bosh_azure_cpi/spec/unit/light_stemcell_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/light_stemcell_manager_spec.rb @@ -156,7 +156,7 @@ expect do light_stemcell_manager.create_stemcell(stemcell_properties) - end.to raise_error /Cannot find the light stemcell/ + end.to raise_error(/Cannot find the light stemcell/) end end end @@ -229,7 +229,7 @@ it 'should throw an error' do expect do light_stemcell_manager.get_stemcell_info(stemcell_name) - end.to raise_error /The light stemcell '#{stemcell_name}' does not exist in the storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}'/ + end.to raise_error(/The light stemcell '#{stemcell_name}' does not exist in the storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}'/) end end diff --git a/src/bosh_azure_cpi/spec/unit/logger_spec.rb b/src/bosh_azure_cpi/spec/unit/logger_spec.rb index 895b77e5b..f4264ce86 100644 --- a/src/bosh_azure_cpi/spec/unit/logger_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/logger_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' describe Bosh::AzureCloud::CPILogger do - context '#set_request_id' do + describe '#set_request_id' do let(:message) { 'fake-message' } let(:request_id) { 'fake-req-id' } let(:log_file) { '/tmp/cpi-fake-logger.log' } diff --git a/src/bosh_azure_cpi/spec/unit/models/disk_id_spec.rb b/src/bosh_azure_cpi/spec/unit/models/disk_id_spec.rb index 30645322b..641c3368b 100644 --- a/src/bosh_azure_cpi/spec/unit/models/disk_id_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/models/disk_id_spec.rb @@ -7,6 +7,7 @@ describe '#self.create' do let(:uuid) { 'c5fb8cae-c3de-48b9-af8f-c17d373e6ff4' } + before do allow(SecureRandom).to receive(:uuid).and_return(uuid) end @@ -17,6 +18,7 @@ let(:storage_account_name) { '6slyzrx7ypji2cfdefaultsa' } let(:disk_name) { "bosh-data-#{uuid}" } let(:id_str) { "caching:#{caching};disk_name:#{disk_name};storage_account_name:#{storage_account_name}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.create(caching, use_managed_disks, storage_account_name: storage_account_name) expect(disk_id.to_s).to eq(id_str) @@ -32,6 +34,7 @@ let(:rg_name) { 'another-resource-group-name' } let(:disk_name) { "bosh-disk-data-#{uuid}" } let(:id_str) { "caching:#{caching};disk_name:#{disk_name};resource_group_name:#{rg_name}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.create(caching, use_managed_disks, resource_group_name: rg_name) expect(disk_id.to_s).to eq(id_str) @@ -40,7 +43,7 @@ expect(disk_id.resource_group_name).to eq(rg_name) expect do disk_id.storage_account_name - end.to raise_error /This function should only be called for unmanaged disks/ + end.to raise_error(/This function should only be called for unmanaged disks/) end end end @@ -53,8 +56,10 @@ context 'when id_str is v1 format' do context 'with unmanaged disks' do let(:storage_account_name) { '6slyzrx7ypji2cfdefaultsa' } # There should be no "-" in the storage account name + context 'when the id is disk id' do let(:id_str) { "bosh-data-#{storage_account_name}-#{uuid}-#{caching}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(disk_id.to_s).to eq(id_str) @@ -67,6 +72,7 @@ context 'when the id is snapshot id' do let(:id_str) { "bosh-data-#{storage_account_name}-#{uuid}-#{caching}--snapshottime" } + it 'should return a correct snapshot id' do snapshot_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(snapshot_id.to_s).to eq(id_str) @@ -77,6 +83,7 @@ context 'with managed disks' do let(:id_str) { "bosh-disk-data-#{uuid}-#{caching}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(disk_id.to_s).to eq(id_str) @@ -85,7 +92,7 @@ expect(disk_id.resource_group_name).to eq(default_resource_group_name) expect do disk_id.storage_account_name - end.to raise_error /This function should only be called for unmanaged disks/ + end.to raise_error(/This function should only be called for unmanaged disks/) end end end @@ -93,9 +100,11 @@ context 'when id_str is v2 format' do context 'with unmanaged disks' do let(:storage_account_name) { '6slyzrx7ypji2cfdefaultsa' } # There should be no "-" in the storage account name + context 'when the id is disk id' do let(:disk_name) { "bosh-data-#{uuid}" } let(:id_str) { "caching:#{caching};disk_name:#{disk_name};storage_account_name:#{storage_account_name}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(disk_id.to_s).to eq(id_str) @@ -109,6 +118,7 @@ context 'when the id is snapshot id' do let(:snapshot_disk_name) { "bosh-data-#{uuid}--snapshottime" } let(:id_str) { "caching:#{caching};disk_name:#{snapshot_disk_name};storage_account_name:#{storage_account_name}" } + it 'should return a correct snapshot id' do snapshot_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(snapshot_id.to_s).to eq(id_str) @@ -119,8 +129,10 @@ context 'with managed disks' do let(:disk_name) { "bosh-disk-data-#{uuid}" } + context 'with resource_group_name is default_resource_group_name' do let(:id_str) { "caching:#{caching};disk_name:#{disk_name};resource_group_name:#{default_resource_group_name}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(disk_id.to_s).to eq(id_str) @@ -129,13 +141,14 @@ expect(disk_id.resource_group_name).to eq(default_resource_group_name) expect do disk_id.storage_account_name - end.to raise_error /This function should only be called for unmanaged disks/ + end.to raise_error(/This function should only be called for unmanaged disks/) end end context 'with resource_group_name is not default_resource_group_name' do let(:rg_name) { 'another-resource-group-name' } let(:id_str) { "caching:#{caching};disk_name:#{disk_name};resource_group_name:#{rg_name}" } + it 'should return a correct disk id' do disk_id = Bosh::AzureCloud::DiskId.parse(id_str, default_resource_group_name) expect(disk_id.to_s).to eq(id_str) @@ -144,7 +157,7 @@ expect(disk_id.resource_group_name).to eq(rg_name) expect do disk_id.storage_account_name - end.to raise_error /This function should only be called for unmanaged disks/ + end.to raise_error(/This function should only be called for unmanaged disks/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/models/obj_id_spec.rb b/src/bosh_azure_cpi/spec/unit/models/obj_id_spec.rb index c665e5859..1f6c213f5 100644 --- a/src/bosh_azure_cpi/spec/unit/models/obj_id_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/models/obj_id_spec.rb @@ -6,6 +6,7 @@ describe '#self.parse_with_resource_group' do let(:plain_id) { 'mock_plain_id' } let(:resource_group_name) { 'mock_rg' } + context 'when parse with resource group' do it 'the resource group value is correct' do expect do @@ -18,11 +19,12 @@ context 'when parse with wrong format string' do let(:wrong_id_str) { 'mock_plain_id;ak:av' } + it 'should raise error' do ErrorMsg = Bosh::AzureCloud::ErrorMsg expect do Bosh::AzureCloud::ResObjectId.parse_with_resource_group(wrong_id_str, resource_group_name) - end.to raise_error /#{ErrorMsg::OBJ_ID_KEY_VALUE_FORMAT_ERROR}/ + end.to raise_error(/#{ErrorMsg::OBJ_ID_KEY_VALUE_FORMAT_ERROR}/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/models/security_group_spec.rb b/src/bosh_azure_cpi/spec/unit/models/security_group_spec.rb index 897fd8f21..94d32bd83 100644 --- a/src/bosh_azure_cpi/spec/unit/models/security_group_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/models/security_group_spec.rb @@ -11,6 +11,7 @@ 'name' => sg_name } end + describe '#self.parse_security_group' do context 'when resource group specified' do it 'the resource group value is correct' do @@ -24,6 +25,7 @@ describe '#to_s' do context 'when called' do let(:sg_string) { "name: #{sg_name}, resource_group_name: #{resource_group_name}" } + it 'should return the correct string' do security_group = Bosh::AzureCloud::SecurityGroup.parse_security_group(security_group_with_resource_group) expect(security_group.to_s).to eq(sg_string) diff --git a/src/bosh_azure_cpi/spec/unit/models/vm_cloud_props_spec.rb b/src/bosh_azure_cpi/spec/unit/models/vm_cloud_props_spec.rb index 83ddde721..f8c3e36a5 100644 --- a/src/bosh_azure_cpi/spec/unit/models/vm_cloud_props_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/models/vm_cloud_props_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/cloud/shared_stuff.rb' +require 'unit/cloud/shared_stuff' describe Bosh::AzureCloud::VMCloudProps do include_context 'shared stuff' @@ -70,7 +70,7 @@ it 'should raise an error' do expect do Bosh::AzureCloud::VMCloudProps.new(vm_cloud_properties, azure_config_managed) - end.to raise_error /'#{zone}' is not a valid zone/ + end.to raise_error(/'#{zone}' is not a valid zone/) end end @@ -86,7 +86,7 @@ it 'should raise an error' do expect do Bosh::AzureCloud::VMCloudProps.new(vm_cloud_properties, azure_config_managed) - end.to raise_error /Only one of 'availability_zone' and 'availability_set' is allowed to be configured for the VM but you have configured both/ + end.to raise_error(/Only one of 'availability_zone' and 'availability_set' is allowed to be configured for the VM but you have configured both/) end end @@ -417,7 +417,7 @@ end end - context '#managed_identity' do + describe '#managed_identity' do context 'when default_managed_identity is not specified in global configurations' do context 'when managed_identity is not specified in vm_extensions' do let(:vm_cloud_props) do diff --git a/src/bosh_azure_cpi/spec/unit/network_configurator_spec.rb b/src/bosh_azure_cpi/spec/unit/network_configurator_spec.rb index cea127fd6..aaef6486a 100644 --- a/src/bosh_azure_cpi/spec/unit/network_configurator_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/network_configurator_spec.rb @@ -141,7 +141,7 @@ expect do Bosh::AzureCloud::NetworkConfigurator.new(azure_config, network_spec) end.to raise_error Bosh::Clouds::CloudError, "Invalid network type 'foo' for Azure, " \ - "can only handle 'dynamic', 'vip', or 'manual' network types" + "can only handle 'dynamic', 'vip', or 'manual' network types" end end diff --git a/src/bosh_azure_cpi/spec/unit/network_spec.rb b/src/bosh_azure_cpi/spec/unit/network_spec.rb index 5d76a2675..6a1e1c025 100644 --- a/src/bosh_azure_cpi/spec/unit/network_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/network_spec.rb @@ -6,12 +6,12 @@ let(:azure_config) { mock_azure_config } let(:network_name) { 'fake-name' } - context '#initialize' do + describe '#initialize' do context 'when spec is invalid' do it 'should raise an error' do expect do Bosh::AzureCloud::Network.new(azure_config, network_name, nil) - end.to raise_error /Invalid spec, Hash expected/ + end.to raise_error(/Invalid spec, Hash expected/) end end @@ -57,7 +57,7 @@ end end - context '#spec' do + describe '#spec' do let(:network_spec) do { 'ip' => 'fake-ip', diff --git a/src/bosh_azure_cpi/spec/unit/stemcell_manager2_spec.rb b/src/bosh_azure_cpi/spec/unit/stemcell_manager2_spec.rb index 6abf586a5..66854726f 100644 --- a/src/bosh_azure_cpi/spec/unit/stemcell_manager2_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/stemcell_manager2_spec.rb @@ -164,7 +164,7 @@ it 'should raise an error' do expect do stemcell_manager2.get_user_image_info(stemcell_name, storage_account_type, location) - end.to raise_error /Failed to get user image for the stemcell '#{stemcell_name}'/ + end.to raise_error(/Failed to get user image for the stemcell '#{stemcell_name}'/) end end @@ -354,7 +354,7 @@ .and_call_original expect do stemcell_manager2.get_user_image_info(stemcell_name, storage_account_type, location) - end.to raise_error /Error when copying blobs/ + end.to raise_error(/Error when copying blobs/) end end end @@ -372,7 +372,7 @@ it 'raise an error' do expect do stemcell_manager2.get_user_image_info(stemcell_name, storage_account_type, location) - end.to raise_error /Error when creating storage account/ + end.to raise_error(/Error when creating storage account/) end end end @@ -442,6 +442,7 @@ location: location } end + before do allow(storage_account_manager).to receive(:default_storage_account) .and_return(default_storage_account) diff --git a/src/bosh_azure_cpi/spec/unit/stemcell_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/stemcell_manager_spec.rb index 7905c9341..9801df490 100644 --- a/src/bosh_azure_cpi/spec/unit/stemcell_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/stemcell_manager_spec.rb @@ -72,6 +72,7 @@ allow(Open3).to receive(:capture2e).and_return(['', double('status', exitstatus: 0)]) end + it 'creates the stemcell' do expect(blob_manager).to receive(:create_page_blob) @@ -145,7 +146,7 @@ expect do stemcell_manager.has_stemcell?(storage_account_name, stemcell_name) - end.to raise_error /The status of the stemcell #{stemcell_name} in the storage account #{storage_account_name} is unknown/ + end.to raise_error(/The status of the stemcell #{stemcell_name} in the storage account #{storage_account_name} is unknown/) end end @@ -169,6 +170,7 @@ } ] end + before do allow(table_manager).to receive(:query_entities) .and_return(entities_first_query, entities_second_query) @@ -201,10 +203,12 @@ } ] end + before do allow(Time).to receive(:new).and_return(time_now, (time_now + 1.1)) allow_any_instance_of(Object).to receive(:sleep).and_return(nil) end + it 'should raise an error' do expect(blob_manager).not_to receive(:get_blob_properties) # The first query is in get_blob_properties, the second and third queries are in wait_stemcell_copy @@ -218,7 +222,7 @@ expect do stemcell_manager.has_stemcell?(storage_account_name, stemcell_name) - end.to raise_error /The operation of copying the stemcell #{stemcell_name} to the storage account #{storage_account_name} timeouts/ + end.to raise_error(/The operation of copying the stemcell #{stemcell_name} to the storage account #{storage_account_name} timeouts/) end end @@ -254,7 +258,7 @@ expect do stemcell_manager.has_stemcell?(storage_account_name, stemcell_name) - end.to raise_error /The operation of copying the stemcell #{stemcell_name} to the storage account #{storage_account_name} timeouts/ + end.to raise_error(/The operation of copying the stemcell #{stemcell_name} to the storage account #{storage_account_name} timeouts/) end end end @@ -332,7 +336,7 @@ it 'should get one exception' do expect do stemcell_manager.has_stemcell?(storage_account_name, stemcell_name) - end.to raise_error /insert into table failed./ + end.to raise_error(/insert into table failed./) end end end @@ -377,7 +381,7 @@ it 'should throw an error' do expect do stemcell_manager.get_stemcell_info(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME, stemcell_name) - end.to raise_error /The stemcell '#{stemcell_name}' does not exist in the storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}'/ + end.to raise_error(/The stemcell '#{stemcell_name}' does not exist in the storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}'/) end end diff --git a/src/bosh_azure_cpi/spec/unit/storage_account_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/storage_account_manager_spec.rb index b7c6aeaa5..0a062f417 100644 --- a/src/bosh_azure_cpi/spec/unit/storage_account_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/storage_account_manager_spec.rb @@ -19,6 +19,7 @@ describe '#generate_storage_account_name' do context 'when the first generated name is available' do let(:storage_account_name) { '386ebba59c883c7d15b419b3' } + before do allow(SecureRandom).to receive(:hex).with(12).and_return(storage_account_name) allow(azure_client).to receive(:check_storage_account_name_availability).with(storage_account_name) @@ -36,6 +37,7 @@ context 'when the first generated name is not available, and the second one is available' do let(:storage_account_name_unavailable) { '386ebba59c883c7d15b419b3' } let(:storage_account_name_available) { 'db49daf2fbbf100575a3af9c' } + before do allow(SecureRandom).to receive(:hex).with(12).and_return(storage_account_name_unavailable, storage_account_name_available) allow(azure_client).to receive(:check_storage_account_name_availability).with(storage_account_name_unavailable) @@ -95,6 +97,7 @@ message: 'fake-message' } end + before do allow(storage_account_manager).to receive(:find_storage_account_by_name).and_return(nil) allow(azure_client).to receive(:check_storage_account_name_availability).with(name).and_return(result) @@ -115,6 +118,7 @@ message: 'fake-message' } end + before do allow(storage_account_manager).to receive(:find_storage_account_by_name).and_return(nil) allow(azure_client).to receive(:check_storage_account_name_availability).with(name).and_return(result) @@ -383,6 +387,7 @@ name: MOCK_DEFAULT_STORAGE_ACCOUNT_NAME } end + before do allow(azure_client).to receive(:get_storage_account_by_name).with(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME).and_return(default_storage_account) end @@ -396,7 +401,7 @@ it 'should raise an error' do expect do storage_account_manager.default_storage_account - end.to raise_error /The default storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}' is specified in Global Configuration, but it does not exist./ + end.to raise_error(/The default storage account '#{MOCK_DEFAULT_STORAGE_ACCOUNT_NAME}' is specified in Global Configuration, but it does not exist./) end end @@ -429,6 +434,7 @@ tags: STEMCELL_STORAGE_ACCOUNT_TAGS } end + before do allow(azure_client).to receive(:get_storage_account_by_name).with(MOCK_DEFAULT_STORAGE_ACCOUNT_NAME).and_return(default_storage_account) end @@ -473,6 +479,7 @@ } ] end + before do allow(azure_client).to receive(:list_storage_accounts).and_return(storage_accounts) allow(azure_client).to receive(:get_resource_group) @@ -502,7 +509,7 @@ before do allow(Azure::Storage::Table::TableService).to receive(:new).with(client: azure_storage_client) - .and_return(table_service) + .and_return(table_service) allow(Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter).to receive(:new) .and_return(exponential_retry) allow(table_service).to receive(:with_filter).with(exponential_retry) @@ -694,6 +701,7 @@ context 'When no storage account is found in the resource group location' do let(:targeted_storage_account) { { name: 'account1' } } + before do allow(azure_client).to receive(:list_storage_accounts).and_return([]) allow(azure_client).to receive(:get_resource_group) diff --git a/src/bosh_azure_cpi/spec/unit/table_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/table_manager_spec.rb index 12d0754e4..871c0dd92 100644 --- a/src/bosh_azure_cpi/spec/unit/table_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/table_manager_spec.rb @@ -49,7 +49,7 @@ .and_return(storage_account) allow(Azure::Storage::Table::TableService).to receive(:new).with(client: azure_storage_client) - .and_return(table_service) + .and_return(table_service) allow(Azure::Storage::Common::Core::Filter::ExponentialRetryPolicyFilter).to receive(:new) .and_return(exponential_retry) allow(table_service).to receive(:with_filter).with(exponential_retry) @@ -101,7 +101,7 @@ def initialize it 'should raise an error' do expect do table_manager.has_table?(table_name) - end.to raise_error /Not-404-Error/ + end.to raise_error(/Not-404-Error/) end end end @@ -177,7 +177,7 @@ def initialize it 'should raise an error' do expect do table_manager.insert_entity(table_name, entity) - end.to raise_error /Not-409-Error/ + end.to raise_error(/Not-409-Error/) end end end @@ -221,7 +221,7 @@ def initialize it 'should raise an error' do expect do table_manager.delete_entity(table_name, partition_key, row_key) - end.to raise_error /Not-404-Error/ + end.to raise_error(/Not-404-Error/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_handler_spec.rb b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_handler_spec.rb index 228acd735..095a3d624 100644 --- a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_handler_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_handler_spec.rb @@ -42,6 +42,7 @@ context 'when the last post happened more than 1 minutes ago' do let(:now) { Time.new.round } let(:last_post_timestamp) { now - 61 } + before do allow(Time).to receive(:new).and_return(now) allow(event_handler).to receive(:get_last_post_timestamp).and_return(last_post_timestamp) @@ -167,7 +168,7 @@ expect(logger).to receive(:warn).with(/unknown error/) expect do event_handler.send(:collect_events, event_number) - end.to raise_error /unknown error/ + end.to raise_error(/unknown error/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_list_spec.rb b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_list_spec.rb index c893ca5db..b87f590a3 100644 --- a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_list_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_list_spec.rb @@ -6,6 +6,7 @@ describe '#initialize' do context 'when event_list is an Array' do let(:param) { [] } + it 'should not raise an error' do expect do Bosh::AzureCloud::TelemetryEventList.new(param) @@ -15,10 +16,11 @@ context 'when event_list is not an Array' do let(:param) { nil } + it 'should raise an error' do expect do Bosh::AzureCloud::TelemetryEventList.new(param) - end.to raise_error /event_list must be an Array/ + end.to raise_error(/event_list must be an Array/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_param_spec.rb b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_param_spec.rb index 17cfd821c..6a07129e9 100644 --- a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_param_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_event_param_spec.rb @@ -105,6 +105,7 @@ context 'when type of value is unknown' do let(:obj) { double('unknown-type') } + it 'should return with right value' do expect(telemetry_event_param.send(:type_of, obj)).to eq('mt:wstr') end diff --git a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_manager_spec.rb b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_manager_spec.rb index 43ced44e9..b949a312d 100644 --- a/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_manager_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/telemetry/telemetry_manager_spec.rb @@ -176,6 +176,7 @@ ).to eq(result) end end + context 'when environment is AzureStack' do let(:telemetry_manager) { Bosh::AzureCloud::TelemetryManager.new(mock_azure_config_merge('enable_telemetry' => true, 'environment' => 'AzureStack')) } let(:result) { 'fake-result' } @@ -222,9 +223,7 @@ expect(file).to receive(:write) end expect(event_handler).to receive(:collect_and_send_events) - expect(telemetry_manager).to receive(:fork) do |&block1| - block1.call - end.exactly(2).times + expect(telemetry_manager).to receive(:fork).and_yield.twice expect do telemetry_manager.send(:_report_event, telemetry_event) diff --git a/src/bosh_azure_cpi/spec/unit/telemetry/wire_client_spec.rb b/src/bosh_azure_cpi/spec/unit/telemetry/wire_client_spec.rb index 1f3e1ac9f..65445e6d4 100644 --- a/src/bosh_azure_cpi/spec/unit/telemetry/wire_client_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/telemetry/wire_client_spec.rb @@ -212,7 +212,7 @@ .and_call_original.twice expect( wire_client.send(:get_endpoint_from_leases_path, lease_path) - ).to eq('168.63.129.16') # Note: a8:3f:81:10 is translated to 168.63.129.16 + ).to eq('168.63.129.16') # NOTE: a8:3f:81:10 is translated to 168.63.129.16 end end @@ -258,7 +258,7 @@ .and_call_original expect( wire_client.send(:get_endpoint_from_leases_path, lease_path) - ).to eq('168.63.129.16') # Note: a8:3f:81:10 is translated to 168.63.129.16 + ).to eq('168.63.129.16') # NOTE: a8:3f:81:10 is translated to 168.63.129.16 end end diff --git a/src/bosh_azure_cpi/spec/unit/utils/bosh_agent_util_spec.rb b/src/bosh_azure_cpi/spec/unit/utils/bosh_agent_util_spec.rb index d58703855..48ff3c852 100644 --- a/src/bosh_azure_cpi/spec/unit/utils/bosh_agent_util_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/utils/bosh_agent_util_spec.rb @@ -1,7 +1,8 @@ +# frozen_string_literal: true + require 'spec_helper' describe Bosh::AzureCloud::BoshAgentUtil do - subject(:agent_util) { described_class.new(uses_registry) } let(:registry_endpoint) { 'http://fake-registry.url/' } @@ -30,7 +31,7 @@ let(:computer_name) { 'fake-computer-name' } before do - allow(config).to receive(:agent).and_return({'mbus' => 'http://u:p@somewhere'}) + allow(config).to receive(:agent).and_return({ 'mbus' => 'http://u:p@somewhere' }) end describe '#user_data_obj' do @@ -38,9 +39,9 @@ let(:uses_registry) { true } let(:expected_user_data) do { - registry: { endpoint: registry_endpoint }, - server: { name: instance_id }, - dns: { nameserver: dns } + registry: { endpoint: registry_endpoint }, + server: { name: instance_id }, + dns: { nameserver: dns } } end @@ -66,7 +67,7 @@ { server: { name: instance_id }, dns: { nameserver: dns }, - 'vm' => {'name' => vm_params[:name]}, + 'vm' => { 'name' => vm_params[:name] }, 'agent_id' => agent_id, 'networks' => { 'network_a' => { @@ -82,7 +83,7 @@ 'system' => '/dev/sda', 'persistent' => {}, 'ephemeral' => { - 'lun' => "0", + 'lun' => '0', 'host_device_id' => '{f8b3781b-1e82-4818-a1c3-63d806ec15bb}', } }, @@ -107,4 +108,4 @@ end end end -end \ No newline at end of file +end diff --git a/src/bosh_azure_cpi/spec/unit/vhd_utils_spec.rb b/src/bosh_azure_cpi/spec/unit/vhd_utils_spec.rb index 7168bd24b..e02a1a06f 100644 --- a/src/bosh_azure_cpi/spec/unit/vhd_utils_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vhd_utils_spec.rb @@ -17,7 +17,7 @@ it 'should succees' do footer = nil expect do - footer = Bosh::AzureCloud::VHDUtils.generate_footer(65_535 * 16 * 63 * 512 - 512) + footer = Bosh::AzureCloud::VHDUtils.generate_footer((65_535 * 16 * 63 * 512) - 512) end.not_to raise_error expect(footer[:geometry]).to eq([655_34, 16, 63].pack('nCC')) end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/accelerated_networking_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/accelerated_networking_spec.rb index ed053465f..b2ce29201 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/accelerated_networking_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/accelerated_networking_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -24,7 +24,7 @@ end # Accelerated Networking - context '#accelerated_networking' do + describe '#accelerated_networking' do context 'when accelerated networking is disbaled in network specs' do before do allow(manual_network).to receive(:accelerated_networking).and_return(false) @@ -37,6 +37,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -55,6 +56,7 @@ 'accelerated_networking' => false ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -73,6 +75,7 @@ 'accelerated_networking' => true ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -97,6 +100,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -115,6 +119,7 @@ 'accelerated_networking' => false ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -133,6 +138,7 @@ 'accelerated_networking' => true ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/application_security_group_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/application_security_group_spec.rb index fb3f78f29..35e344967 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/application_security_group_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/application_security_group_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -40,7 +40,7 @@ end # Application Security Groups - context '#application_security_groups' do + describe '#application_security_groups' do context 'when the application security groups are specified in network specs' do let(:asg_1_name_in_network_spec) { 'fake-asg-1-name-specified-in-network-spec' } let(:asg_1_in_network_spec) do @@ -84,7 +84,7 @@ end.not_to raise_error end - context ' and vm_properties' do + context 'and vm_properties' do let(:asg_1_name_in_vm_properties) { 'fake-asg-1-name-specified-in-resource-pool' } let(:asg_1_in_vm_properties) do { @@ -138,7 +138,7 @@ end # The cases in the below context doesn't care where the asg names is specified. - context '#resource_group_for_application_security_group' do + describe '#resource_group_for_application_security_group' do let(:asg_name) { 'fake-asg-name' } let(:asg) do { @@ -189,6 +189,7 @@ context 'when the resource group name is specified in the network spec' do let(:rg_name_for_asg) { 'resource-group-name-for-application-security-group' } + before do allow(manual_network).to receive(:resource_group_name).and_return(rg_name_for_asg) allow(dynamic_network).to receive(:resource_group_name).and_return(rg_name_for_asg) @@ -254,7 +255,7 @@ expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the application security group '#{asg_name}'/ + end.to raise_error(/Cannot find the application security group '#{asg_name}'/) end end end @@ -262,7 +263,7 @@ end # IP Forwarding - context '#ip_forwarding' do + describe '#ip_forwarding' do context 'when ip forwarding is disbaled in network specs' do before do allow(manual_network).to receive(:ip_forwarding).and_return(false) @@ -275,6 +276,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -293,6 +295,7 @@ 'ip_forwarding' => false ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -311,6 +314,7 @@ 'ip_forwarding' => true ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -335,6 +339,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -353,6 +358,7 @@ 'ip_forwarding' => false ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -371,6 +377,7 @@ 'ip_forwarding' => true ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -385,7 +392,7 @@ end # Accelerated Networking - context '#accelerated_networking' do + describe '#accelerated_networking' do context 'when accelerated networking is disbaled in network specs' do before do allow(manual_network).to receive(:accelerated_networking).and_return(false) @@ -398,6 +405,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -416,6 +424,7 @@ 'accelerated_networking' => false ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -434,6 +443,7 @@ 'accelerated_networking' => true ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -458,6 +468,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -476,6 +487,7 @@ 'accelerated_networking' => false ) end + it 'should disable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -494,6 +506,7 @@ 'accelerated_networking' => true ) end + it 'should enable accelerated networking on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -508,13 +521,13 @@ end # Stemcell - context '#stemcell' do + describe '#stemcell' do context 'when a heavy stemcell is used' do it 'should succeed' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) - expect(azure_client).to receive(:create_network_interface).exactly(2).times + expect(azure_client).to receive(:create_network_interface).twice _, vm_params = vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) expect(vm_params[:name]).to eq(vm_name) expect(vm_params[:image_uri]).to eq(stemcell_uri) @@ -597,7 +610,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: [application_gateway] )).once @@ -625,7 +638,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: [application_gateway] )) @@ -745,7 +758,7 @@ end context 'when AzureAsynchronousError is raised once and AzureAsynchronousError.status is Failed' do - context ' and use_managed_disks is false' do + context 'and use_managed_disks is false' do it 'should succeed' do count = 0 allow(azure_client).to receive(:create_virtual_machine) do @@ -771,7 +784,7 @@ end end - context ' and use_managed_disks is true' do + context 'and use_managed_disks is true' do it 'should succeed' do count = 0 allow(azure_client).to receive(:create_virtual_machine) do diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_set_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_set_spec.rb index 62d6b4979..7b24d1e93 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_set_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_set_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -19,7 +19,7 @@ end # Availability Set - context '#availability_set' do + describe '#availability_set' do context 'when availability set is not created' do let(:availability_set_name) { SecureRandom.uuid.to_s } let(:vm_props) do @@ -44,11 +44,11 @@ .with("#{CPI_LOCK_PREFIX_AVAILABILITY_SET}-#{availability_set_name}", File::LOCK_EX) .and_call_original - expect(azure_client).to receive(:delete_network_interface).exactly(2).times + expect(azure_client).to receive(:delete_network_interface).twice expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /availability set is not created/ + end.to raise_error(/availability set is not created/) end end @@ -192,6 +192,7 @@ sku_tier: 'Standard' } end + before do allow(disk_manager2).to receive(:get_data_disk) .with(disk_id_object) @@ -246,6 +247,7 @@ sku_tier: 'Premium' } end + before do allow(disk_manager2).to receive(:get_data_disk) .with(disk_id_object) @@ -300,6 +302,7 @@ sku_tier: 'Standard' } end + before do allow(disk_id_object).to receive(:storage_account_name) .and_return(storage_account_name) @@ -358,6 +361,7 @@ sku_tier: 'Premium' } end + before do allow(disk_id_object).to receive(:storage_account_name) .and_return(storage_account_name) @@ -566,7 +570,7 @@ context 'when the length of availability_set name is greater than 80' do let(:env) do { - 'bosh' => { 'group' => 'a' * 80 + 'group' * 8 } + 'bosh' => { 'group' => ('a' * 80) + ('group' * 8) } } end @@ -635,6 +639,7 @@ 'platform_fault_domain_count' => 1 ) end + before do avset_params[:managed] = false end @@ -666,6 +671,7 @@ }, azure_config_managed ) end + before do avset_params[:managed] = true end @@ -712,6 +718,7 @@ }, azure_config ) end + before do avset_params[:platform_update_domain_count] = 5 avset_params[:platform_fault_domain_count] = 3 @@ -743,6 +750,7 @@ }, azure_config_managed ) end + before do avset_params[:platform_update_domain_count] = 5 avset_params[:platform_fault_domain_count] = 2 @@ -851,11 +859,11 @@ it 'should not create the availability set and then raise an error' do expect(azure_client).not_to receive(:create_availability_set) - expect(azure_client).to receive(:delete_network_interface).exactly(2).times + expect(azure_client).to receive(:delete_network_interface).twice expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /availability set '#{availability_set_name}' already exists, but in a different location/ + end.to raise_error(/availability set '#{availability_set_name}' already exists, but in a different location/) end end @@ -970,7 +978,7 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /availability set '.+' already exists. It's not allowed to update it from managed to unmanaged./ + end.to raise_error(/availability set '.+' already exists. It's not allowed to update it from managed to unmanaged./) end end end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_zone_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_zone_spec.rb index e7bb8b87f..ad2e742df 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_zone_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/availability_zone_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/boot_diagnostics_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/boot_diagnostics_spec.rb index 660dcfa93..c2db4c4b9 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/boot_diagnostics_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/boot_diagnostics_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/dynamic_public_ip_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/dynamic_public_ip_spec.rb index b8b784f7f..ad8be9b80 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/dynamic_public_ip_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/dynamic_public_ip_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -69,7 +69,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: [application_gateway] )).once end @@ -300,7 +300,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: [application_gateway] )).once end @@ -425,7 +425,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: application_gateway )).once allow(azure_client).to receive(:get_application_gateway_by_name) @@ -541,7 +541,7 @@ public_ip: dynamic_public_ip, subnet: subnet, tags: tags, - load_balancers: [ load_balancer ], + load_balancers: [load_balancer], application_gateways: [application_gateway] )) @@ -662,7 +662,7 @@ end context 'when AzureAsynchronousError is raised once and AzureAsynchronousError.status is Failed' do - context ' and use_managed_disks is false' do + context 'and use_managed_disks is false' do it 'should succeed' do count = 0 allow(azure_client).to receive(:create_virtual_machine) do @@ -688,7 +688,7 @@ end end - context ' and use_managed_disks is true' do + context 'and use_managed_disks is true' do it 'should succeed' do count = 0 allow(azure_client).to receive(:create_virtual_machine) do diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/get_root_disk_type_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/get_root_disk_type_spec.rb index 5723f16db..ffc7bf2e9 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/get_root_disk_type_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/get_root_disk_type_spec.rb @@ -1,14 +1,14 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' # The following variables are defined in shared_stuff.rb. You can override it if needed. # - default_security_group - context '#root_disk_type' do + describe '#root_disk_type' do context 'when only instance_type is specified' do context 'when instance_type does not support SSD disks' do let(:vm_props) do diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/invalid_option_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/invalid_option_spec.rb index f9d3f8bff..22e729e0e 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/invalid_option_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/invalid_option_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -39,7 +39,7 @@ it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name\/fake-subnet-name' in the resource group '#{MOCK_RESOURCE_GROUP_NAME}'} + end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name/fake-subnet-name' in the resource group '#{MOCK_RESOURCE_GROUP_NAME}'} end end @@ -66,7 +66,7 @@ it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the network security group 'fake-default-nsg-name'/ + end.to raise_error(/Cannot find the network security group 'fake-default-nsg-name'/) end end end @@ -100,7 +100,7 @@ .and_return(nil) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name\/fake-subnet-name' in the resource group 'fake-resource-group-name'} + end.to raise_error %r{Cannot find the subnet 'fake-virtual-network-name/fake-subnet-name' in the resource group 'fake-resource-group-name'} end end @@ -120,7 +120,7 @@ it 'should raise an error' do expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the network security group 'fake-default-nsg-name'/ + end.to raise_error(/Cannot find the network security group 'fake-default-nsg-name'/) end end end @@ -147,7 +147,7 @@ expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the public IP address/ + end.to raise_error(/Cannot find the public IP address/) end end @@ -176,7 +176,7 @@ expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the public IP address/ + end.to raise_error(/Cannot find the public IP address/) end end end @@ -198,7 +198,7 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the load balancer/ + end.to raise_error(/Cannot find the load balancer/) end end @@ -222,7 +222,7 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the application gateway/ + end.to raise_error(/Cannot find the application gateway/) end end @@ -256,7 +256,7 @@ expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /network interface is not created/ + end.to raise_error(/network interface is not created/) end end @@ -290,7 +290,7 @@ expect(azure_client).to receive(:delete_network_interface).once expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /network interface is not created/ + end.to raise_error(/network interface is not created/) end end @@ -311,7 +311,7 @@ expect(azure_client).to receive(:delete_public_ip).with(MOCK_RESOURCE_GROUP_NAME, vm_name) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /network interface is not created/ + end.to raise_error(/network interface is not created/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/ip_forwarding_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/ip_forwarding_spec.rb index 4606510e2..ba5e36c4c 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/ip_forwarding_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/ip_forwarding_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -21,7 +21,7 @@ end # IP Forwarding - context '#ip_forwarding' do + describe '#ip_forwarding' do context 'when ip forwarding is disbaled in network specs' do before do allow(manual_network).to receive(:ip_forwarding).and_return(false) @@ -34,6 +34,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -52,6 +53,7 @@ 'ip_forwarding' => false ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -70,6 +72,7 @@ 'ip_forwarding' => true ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -94,6 +97,7 @@ 'instance_type' => 'Standard_D1' ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -112,6 +116,7 @@ 'ip_forwarding' => false ) end + it 'should disable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) @@ -130,6 +135,7 @@ 'ip_forwarding' => true ) end + it 'should enable ip forwarding on the network interface' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/managed_identity_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/managed_identity_spec.rb index ce8fc6c12..1d81539e5 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/managed_identity_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/managed_identity_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -20,7 +20,7 @@ allow(azure_client).to receive(:create_virtual_machine) end - context '#managed_identity' do + describe '#managed_identity' do context 'when managed identity is nil in vm_props' do let(:vm_props) do props_factory.parse_vm_props( diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/network_security_group_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/network_security_group_spec.rb index 7baa4171e..595ab992c 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/network_security_group_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/network_security_group_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -24,7 +24,7 @@ end # Network Security Group - context '#network_security_group' do + describe '#network_security_group' do context 'when the network security group is not specified in the global configuration' do let(:azure_config_without_default_security_group) do mock_azure_config_merge( @@ -79,7 +79,7 @@ expect(azure_client).not_to receive(:delete_virtual_machine) expect do vm_manager_without_default_security_group.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot specify an empty string to the network security group/ + end.to raise_error(/Cannot specify an empty string to the network security group/) end end @@ -94,7 +94,7 @@ end.not_to raise_error end - context ' and network specs' do + context 'and network specs' do let(:nsg_name_in_network_spec) { 'fake-nsg-name-specified-in-network-spec' } let(:nsg_in_network_spec) do Bosh::AzureCloud::SecurityGroup.new( @@ -128,7 +128,7 @@ end.not_to raise_error end - context ' and vm_properties' do + context 'and vm_properties' do let(:nsg_name_in_vm_properties) { 'fake-nsg-name-specified-in-resource-pool' } let(:security_group_in_vm_properties) do { @@ -167,7 +167,7 @@ end # The cases in the below context doesn't care where the nsg name is specified. - context '#resource_group_for_network_security_group' do + describe '#resource_group_for_network_security_group' do let(:nsg_name) { 'fake-nsg-name' } let(:security_group) do { @@ -206,6 +206,7 @@ context 'when the resource group name is specified in the network spec' do let(:rg_name_for_nsg) { 'resource-group-name-for-network-security-group' } + before do allow(manual_network).to receive(:resource_group_name) .and_return(rg_name_for_nsg) @@ -275,7 +276,7 @@ expect(azure_client).not_to receive(:delete_network_interface) expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /Cannot find the network security group '#{nsg_name}'/ + end.to raise_error(/Cannot find the network security group '#{nsg_name}'/) end end end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/resource_group_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/resource_group_spec.rb index ae7ce5972..3c5242a4f 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/resource_group_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/resource_group_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/stemcell_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/stemcell_spec.rb index 3dc8966ec..e9526ea99 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/stemcell_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/stemcell_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -21,13 +21,13 @@ end # Stemcell - context '#stemcell' do + describe '#stemcell' do context 'when a heavy stemcell is used' do it 'should succeed' do expect(azure_client).not_to receive(:delete_virtual_machine) expect(azure_client).not_to receive(:delete_network_interface) - expect(azure_client).to receive(:create_network_interface).exactly(2).times + expect(azure_client).to receive(:create_network_interface).twice _, vm_params = vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) expect(vm_params[:name]).to eq(vm_name) expect(vm_params[:image_uri]).to eq(stemcell_uri) diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/tags_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/tags_spec.rb index 0735935a4..319f2da45 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/tags_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/tags_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -30,22 +30,22 @@ end context 'when VM is created' do - context '#tags' do + describe '#tags' do context 'when tags is specified in vm_types or vm_extensions' do it 'should set the tags for the VM' do expect(azure_client).to receive(:create_virtual_machine) - .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: custom_tags.merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) + .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: custom_tags.merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, anything, anything, anything) end end context 'when tags are specified in the incoming env' do - let(:env) { {"bosh" => {"tags" => {'tag-name-1' => 'value-from-env', 'tag-name-3' => 'other-env-value'}}} } + let(:env) { { 'bosh' => { 'tags' => { 'tag-name-1' => 'value-from-env', 'tag-name-3' => 'other-env-value' } } } } it 'should set the tags for the VM' do expect(azure_client).to receive(:create_virtual_machine) - .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: env['bosh']['tags'].merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) - vm_manager.create(bosh_vm_meta, location, props_factory.parse_vm_props({'instance_type' => 'Standard_D1'}), disk_cids, network_configurator, env, anything, anything, anything) + .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: env['bosh']['tags'].merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) + vm_manager.create(bosh_vm_meta, location, props_factory.parse_vm_props({ 'instance_type' => 'Standard_D1' }), disk_cids, network_configurator, env, anything, anything, anything) end context 'when tags are also specified in vm_types' do @@ -56,7 +56,7 @@ 'tag-name-3' => 'other-env-value' } expect(azure_client).to receive(:create_virtual_machine) - .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: expected_tags.merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) + .with(MOCK_RESOURCE_GROUP_NAME, hash_including(tags: expected_tags.merge(Bosh::AzureCloud::Helpers::AZURE_TAGS)), any_args) vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, anything, anything, anything) end end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/use_config_disk_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/use_config_disk_spec.rb index 4f9bae0f9..11b42fe3c 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/use_config_disk_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/use_config_disk_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' # RSpec::Matchers.define :need_mock_command do # match { |actual| { actual.include?('mount') || actual.include?('mkfs.ext4') } } @@ -26,15 +26,16 @@ allow(agent_util).to receive(:meta_data_obj).and_return({}) allow(agent_util).to receive(:encode_user_data).and_return(Base64.strict_encode64(JSON.dump({}))) end + context 'when use config disk' do context 'when everything ok' do it 'should prepare config disk' do expect(azure_client).to receive(:create_virtual_machine) - expect(command_runner).to receive(:run_command).with(/sudo -n mount/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/mkfs/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/sudo -n chown/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/sudo -n umount/).exactly(1).times - expect(command_runner).to receive(:run_command).exactly(2).times.and_call_original + expect(command_runner).to receive(:run_command).with(/sudo -n mount/).once + expect(command_runner).to receive(:run_command).with(/mkfs/).once + expect(command_runner).to receive(:run_command).with(/sudo -n chown/).once + expect(command_runner).to receive(:run_command).with(/sudo -n umount/).once + expect(command_runner).to receive(:run_command).twice.and_call_original expect(Bosh::AzureCloud::CommandRunner).to receive(:new).and_return(command_runner) @@ -48,18 +49,19 @@ end.not_to raise_error end end + context 'when mkfs failed' do it 'should raise an error and clean up' do expect(Bosh::AzureCloud::CommandRunner).to receive(:new).and_return(command_runner) expect(command_runner).to receive(:run_command).with(/mkfs/).and_raise('failed to mkfs') - expect(command_runner).to receive(:run_command).with(/sudo -n umount/).exactly(1).times - expect(command_runner).to receive(:run_command).exactly(1).times.and_call_original + expect(command_runner).to receive(:run_command).with(/sudo -n umount/).once + expect(command_runner).to receive(:run_command).once.and_call_original expect(blob_manager).not_to receive(:create_vhd_page_blob) expect(blob_manager).not_to receive(:delete_blob) expect(blob_manager).not_to receive(:get_blob_uri) expect(disk_manager2).not_to receive(:create_disk_from_blob) - expect(azure_client).to receive(:delete_network_interface).exactly(2).times + expect(azure_client).to receive(:delete_network_interface).twice expect do vm_manager_config_disk.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error Bosh::Clouds::CloudError, /Failed to prepare the config disk/ @@ -68,11 +70,11 @@ context 'when create disk failed' do it 'should raise an error and clean up' do - expect(command_runner).to receive(:run_command).with(/sudo -n mount/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/mkfs/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/sudo -n chown/).exactly(1).times - expect(command_runner).to receive(:run_command).with(/sudo -n umount/).exactly(1).times - expect(command_runner).to receive(:run_command).exactly(2).times.and_call_original + expect(command_runner).to receive(:run_command).with(/sudo -n mount/).once + expect(command_runner).to receive(:run_command).with(/mkfs/).once + expect(command_runner).to receive(:run_command).with(/sudo -n chown/).once + expect(command_runner).to receive(:run_command).with(/sudo -n umount/).once + expect(command_runner).to receive(:run_command).twice.and_call_original expect(Bosh::AzureCloud::CommandRunner).to receive(:new).and_return(command_runner) @@ -80,7 +82,7 @@ expect(blob_manager).to receive(:delete_blob) expect(blob_manager).to receive(:get_blob_uri) expect(disk_manager2).to receive(:create_disk_from_blob).and_raise('create disk failed') - expect(azure_client).to receive(:delete_network_interface).exactly(2).times + expect(azure_client).to receive(:delete_network_interface).twice expect do vm_manager_config_disk.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) end.to raise_error Bosh::Clouds::CloudError, /Failed to prepare the config disk/ diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/create/vm_is_not_created_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/create/vm_is_not_created_spec.rb index 1be93217c..cf21973fe 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/create/vm_is_not_created_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/create/vm_is_not_created_spec.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true require 'spec_helper' -require 'unit/vm_manager/create/shared_stuff.rb' +require 'unit/vm_manager/create/shared_stuff' describe Bosh::AzureCloud::VMManager do include_context 'shared stuff for vm manager' @@ -34,7 +34,7 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /virtual machine is not created/ + end.to raise_error(/virtual machine is not created/) end end @@ -81,7 +81,7 @@ .and_call_original expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /virtual machine is not created/ + end.to raise_error(/virtual machine is not created/) end end @@ -103,7 +103,7 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error /cannot delete nic/ + end.to raise_error(/cannot delete nic/) end end end @@ -125,10 +125,10 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -170,10 +170,10 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -194,10 +194,10 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -214,10 +214,10 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -238,14 +238,14 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/The VM fails in provisioning./) expect(error.inspect).to match(/fake error message/) expect(error.inspect).to match(/And an error is thrown in cleanuping VM, os disk or ephemeral disk before retry./) expect(error.inspect).to match(/cannot delete the vm/) # If the cleanup fails, then the VM resources have to be kept expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -269,10 +269,10 @@ expect do vm_manager.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end end @@ -296,10 +296,10 @@ expect do vm_manager2.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -315,10 +315,10 @@ expect do vm_manager2.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).not_to match(/This VM fails in provisioning after multiple retries/) - } + end) end end end @@ -366,10 +366,10 @@ expect do vm_manager_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -386,10 +386,10 @@ expect do vm_manager_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -410,14 +410,14 @@ expect do vm_manager_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/The VM fails in provisioning./) expect(error.inspect).to match(/fake error message/) expect(error.inspect).to match(/And an error is thrown in cleanuping VM, os disk or ephemeral disk before retry./) expect(error.inspect).to match(/cannot delete the vm/) # If the cleanup fails, then the VM resources have to be kept expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -441,10 +441,10 @@ expect do vm_manager_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end end @@ -468,10 +468,10 @@ expect do vm_manager2_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end @@ -487,10 +487,10 @@ expect do vm_manager2_to_keep_failed_vms.create(bosh_vm_meta, location, vm_props, disk_cids, network_configurator, env, agent_util, network_spec, config) - end.to raise_error { |error| + end.to(raise_error do |error| expect(error.inspect).to match(/Bosh::AzureCloud::AzureAsynchronousError/) expect(error.inspect).to match(/This VM fails in provisioning after multiple retries/) - } + end) end end end diff --git a/src/bosh_azure_cpi/spec/unit/vm_manager/delete_spec.rb b/src/bosh_azure_cpi/spec/unit/vm_manager/delete_spec.rb index b2235e8f5..9d1cc4eb9 100644 --- a/src/bosh_azure_cpi/spec/unit/vm_manager/delete_spec.rb +++ b/src/bosh_azure_cpi/spec/unit/vm_manager/delete_spec.rb @@ -55,13 +55,17 @@ .and_return(vm_name) allow(azure_client).to receive(:get_load_balancer_by_name) - .with(resource_group_name, vm_name).and_return(load_balancer) + .with(resource_group_name, vm_name) + .and_return(load_balancer) allow(azure_client).to receive(:get_application_gateway_by_name) - .with(nil, vm_name).and_return(application_gateway) + .with(nil, vm_name) + .and_return(application_gateway) allow(azure_client).to receive(:get_network_interface_by_name) - .with(resource_group_name, vm_name).and_return(network_interface) + .with(resource_group_name, vm_name) + .and_return(network_interface) allow(azure_client).to receive(:get_public_ip_by_name) - .with(resource_group_name, vm_name).and_return(public_ip) + .with(resource_group_name, vm_name) + .and_return(public_ip) allow(azure_client).to receive(:list_network_interfaces_by_keyword) .with(resource_group_name, vm_name).and_return(network_interfaces) @@ -129,6 +133,7 @@ ] } end + before do allow(azure_client).to receive(:get_virtual_machine_by_name) .with(resource_group_name, vm_name).and_return(vm) @@ -169,6 +174,7 @@ ] } end + before do allow(azure_client).to receive(:get_virtual_machine_by_name) .with(resource_group_name, vm_name).and_return(vm) @@ -335,6 +341,7 @@ ] } end + before do allow(azure_client).to receive(:get_virtual_machine_by_name) .with(resource_group_name, vm_name).and_return(vm)