Exemplo n.º 1
0
 def testScopePrompt(self):
   self.mock_client.instanceGroupManagers.Get.Expect(
       messages.ComputeInstanceGroupManagersGetRequest(
           instanceGroupManager='group-1',
           project='fake-project',
           zone='zone-2'),
       test_resources.MakeInstanceGroupManagers(API_VERSION)[0]
   )
   self.StartPatch('googlecloudsdk.core.console.console_io.CanPrompt',
                   return_value=True)
   self.StartPatch('googlecloudsdk.api_lib.compute.zones.service.List',
                   return_value=[
                       messages.Zone(name='zone-1'),
                       messages.Zone(name='zone-2')],
                  )
   self.StartPatch('googlecloudsdk.api_lib.compute.regions.service.List',
                   return_value=[
                       messages.Region(name='region-1')],
                  )
   self._MockAutoscalerRequest(test_resources.MakeAutoscalers(API_VERSION))
   self.WriteInput('3\n')
   self.Run("""
       compute instance-groups managed describe group-1
       """)
   self.AssertErrContains('group-1')
   self.AssertErrContains('zone-1')
   self.AssertErrContains('zone-2')
   self.AssertErrContains('region-1')
Exemplo n.º 2
0
  def testRegionalTableOutput(self):
    self.SetupMockGetRegionalResources([
        test_resources.MakeAutoscalers(api=API_VERSION,
                                       scope_name='region-1',
                                       scope_type='region')[0]])
    self.Run('compute instance-groups managed list --regions=region-1,region-2')
    self.mock_get_regional_resources.assert_any_call(
        service=self.compute.regionInstanceGroups,
        project='my-project',
        requested_regions=set(['region-1']),
        filter_expr=None,
        http=self.mock_http(),
        batch_url=self.batch_url,
        errors=[])

    self.AssertOutputEquals(
        textwrap.dedent("""\
        NAME    LOCATION SCOPE  BASE_INSTANCE_NAME   SIZE TARGET_SIZE INSTANCE_TEMPLATE AUTOSCALED
        group-1 region-1 region test-instance-name-1 0    1           template-1        yes
        group-2 region-1 region test-instance-name-2 3    10          template-2        no
        group-3 region-1 region test-instance-name-3 10   1           template-2        no
        """), normalize_space=True)
    self.AssertErrEquals("""\
    WARNING: Flag `--regions` is deprecated. Use `--filter="region:( REGION ... )"` instead.
    For example `--filter="region:( europe-west1 europe-west2 )"`.
    """, normalize_space=True)
Exemplo n.º 3
0
    def testZoneAndRegion(self):
        self.make_requests.side_effect = iter([
            test_resources.MakeAutoscalers('beta',
                                           scope_type='zone',
                                           scope_name='zone-1'),
            test_resources.MakeAutoscalers('beta',
                                           scope_type='region',
                                           scope_name='region-1'),
            test_resources.MakeInstanceGroupManagers('beta',
                                                     scope_type='zone',
                                                     scope_name='zone-1'),
            test_resources.MakeInstanceGroupManagers('beta',
                                                     scope_type='region',
                                                     scope_name='region-1'),
            [],  # Deleting 0 Autoscalers.
        ])
        self.WriteInput('y')
        self.Run("""
        beta compute instance-groups managed delete
          https://compute.googleapis.com/compute/{0}/projects/my-project/zones/zone-1/instanceGroupManagers/group-1
          https://compute.googleapis.com/compute/{0}/projects/my-project/regions/region-1/instanceGroupManagers/group-2
        """.format(API_VERSION))

        self.AssertErrContains(
            r'The following instance group managers will be deleted:\n'
            r' - [group-1]\n'
            r' - [group-2] in [region-1]')
        self.AssertErrContains('PROMPT_CONTINUE')
        self.CheckRequests(
            self.autoscalers_list_request_zone_1 +
            self.autoscalers_list_request_region_1,
            [(self.compute.autoscalers, 'Delete',
              self.messages.ComputeAutoscalersDeleteRequest(
                  autoscaler='autoscaler-1',
                  project='my-project',
                  zone='zone-1'))],
            [(self.compute.instanceGroupManagers, 'Delete',
              self.messages.ComputeInstanceGroupManagersDeleteRequest(
                  instanceGroupManager='group-1',
                  project='my-project',
                  zone='zone-1')),
             (self.compute.regionInstanceGroupManagers, 'Delete',
              self.messages.ComputeRegionInstanceGroupManagersDeleteRequest(
                  instanceGroupManager='group-2',
                  project='my-project',
                  region='region-1'))],
        )
Exemplo n.º 4
0
  def testAggregatedTableOutput(self):
    self.SetupMockGetRegionalResources([])
    self.SetupMockGetZonalResources([])
    self.list_json.side_effect = [
        resource_projector.MakeSerializable(
            test_resources.MakeInstanceGroupManagers(
                api=API_VERSION, scope_name='zone-1', scope_type='zone') +
            test_resources.MakeInstanceGroupManagers(
                api=API_VERSION, scope_name='region-1', scope_type='region'))
    ]
    self.make_requests.side_effect = [
        [test_resources.MakeAutoscalers(api=API_VERSION,
                                        scope_name='region-1',
                                        scope_type='region')[0],
         test_resources.MakeAutoscalers(api=API_VERSION,
                                        scope_name='zone-1',
                                        scope_type='zone')[0]]]

    self.Run('compute instance-groups managed list')
    self.mock_get_zonal_resources.assert_any_call(
        service=self.compute.instanceGroups,
        project='my-project',
        requested_zones=set(['zone-1']),
        filter_expr=None,
        http=self.mock_http(),
        batch_url=self.batch_url,
        errors=[])
    self.mock_get_regional_resources.assert_any_call(
        service=self.compute.regionInstanceGroups,
        project='my-project',
        requested_regions=set(['region-1']),
        filter_expr=None,
        http=self.mock_http(),
        batch_url=self.batch_url,
        errors=[])

    self.AssertOutputEquals(
        textwrap.dedent("""\
        NAME    LOCATION SCOPE  BASE_INSTANCE_NAME   SIZE TARGET_SIZE INSTANCE_TEMPLATE AUTOSCALED
        group-1 zone-1   zone   test-instance-name-1 0    1           template-1        yes
        group-2 zone-1   zone   test-instance-name-2 3    10          template-2        no
        group-3 zone-1   zone   test-instance-name-3 10   1           template-2        no
        group-1 region-1 region test-instance-name-1 0    1           template-1        yes
        group-2 region-1 region test-instance-name-2 3    10          template-2        no
        group-3 region-1 region test-instance-name-3 10   1           template-2        no
        """), normalize_space=True)
    self.AssertErrEquals('')
Exemplo n.º 5
0
 def testPromptingWithYes(self):
     self.make_requests.side_effect = iter([
         test_resources.MakeAutoscalers(API_VERSION,
                                        scope_type='region',
                                        scope_name='region-1'),
         test_resources.MakeInstanceGroupManagers(API_VERSION,
                                                  scope_type='region',
                                                  scope_name='region-1'),
         [],
     ])
     self.WriteInput('y')
     self.Run("""
     compute instance-groups managed delete group-1 group-2 group-3
       --region region-1
     """)
     self.CheckRequests(
         self.autoscalers_list_request_region_1,
         [(self.compute.regionAutoscalers, 'Delete',
           self.messages.ComputeRegionAutoscalersDeleteRequest(
               autoscaler='autoscaler-1',
               project='my-project',
               region='region-1')),
          (self.compute.regionAutoscalers, 'Delete',
           self.messages.ComputeRegionAutoscalersDeleteRequest(
               autoscaler='autoscaler-2',
               project='my-project',
               region='region-1')),
          (self.compute.regionAutoscalers, 'Delete',
           self.messages.ComputeRegionAutoscalersDeleteRequest(
               autoscaler='autoscaler-3',
               project='my-project',
               region='region-1'))],
         [(self.compute.regionInstanceGroupManagers, 'Delete',
           self.messages.ComputeRegionInstanceGroupManagersDeleteRequest(
               instanceGroupManager='group-1',
               project='my-project',
               region='region-1')),
          (self.compute.regionInstanceGroupManagers, 'Delete',
           self.messages.ComputeRegionInstanceGroupManagersDeleteRequest(
               instanceGroupManager='group-2',
               project='my-project',
               region='region-1')),
          (self.compute.regionInstanceGroupManagers, 'Delete',
           self.messages.ComputeRegionInstanceGroupManagersDeleteRequest(
               instanceGroupManager='group-3',
               project='my-project',
               region='region-1'))],
     )
     self.AssertErrContains(
         r'The following region instance group managers will be deleted:\n'
         r' - [group-1] in [region-1]\n'
         r' - [group-2] in [region-1]\n'
         r' - [group-3] in [region-1]')
     self.AssertErrContains('PROMPT_CONTINUE')
 def _ExpectListAutoscalers(self, group_name=None):
     autoscalers = test_resources.MakeAutoscalers(
         self.api, scope_name=self.location, scope_type=self.scope_string)
     if self.scope is scope_util.ScopeEnum.REGION:
         request = self._MakeListAutoscalersRegionRequest()
     if self.scope is scope_util.ScopeEnum.ZONE:
         request = self._MakeListAutoscalersZoneRequest()
     autoscaler = autoscalers[0]
     if group_name:
         autoscaler.target = autoscaler.target.replace(
             'group-1', group_name)
     self._ExpectRequest(request, [autoscaler])
Exemplo n.º 7
0
 def _SetUpZonal(self, api_version):
     self.SelectApi(api_version)
     self.zone = 'us-central2-a'
     self.scope_params = ('zone', self.zone)
     self.make_requests.side_effect = iter([
         [
             self.messages.Zone(name=self.zone),
         ],
         [
             test_resources.MakeInstanceGroupManagers(
                 api_version, scope_name=self.zone)[0],
         ],
         [
             test_resources.MakeInstanceGroups(self.messages,
                                               api_version,
                                               scope_name=self.zone)[0],
         ],
         [
             test_resources.MakeAutoscalers(api_version,
                                            scope_name=self.zone)[0],
         ],
     ])
     self.zone_1_get_request = [
         (self.compute.zones, 'Get',
          self.messages.ComputeZonesGetRequest(project='my-project',
                                               zone=self.zone))
     ]
     self.zone_ig_list_request = [
         (self.compute.instanceGroups, 'List',
          self.messages.ComputeInstanceGroupsListRequest(
              maxResults=500,
              project='my-project',
              zone=self.zone,
          ))
     ]
     self.zone_as_list_request = [
         (self.compute.autoscalers, 'List',
          self.messages.ComputeAutoscalersListRequest(maxResults=500,
                                                      project='my-project',
                                                      zone=self.zone))
     ]
     self.template_1_uri = (
         '{0}/projects/my-project/global/instanceTemplates/template-1'.
         format(self.compute_uri))
     self.http_health_check_uri = (
         '{0}/projects/my-project/global/httpHealthChecks/health-check-1'.
         format(self.compute_uri))
     self.https_health_check_uri = (
         '{0}/projects/my-project/global/httpsHealthChecks/health-check-2'.
         format(self.compute_uri))
Exemplo n.º 8
0
  def testMultiScopeTableOutput(self):
    self.SetupMockGetZonalResources(
        [test_resources.MakeAutoscalers(API_VERSION)[0]])
    self.Run('compute instance-groups managed list --zones zone-1,zone-2')
    self.mock_get_zonal_resources.assert_any_call(
        service=self.compute.instanceGroups,
        project='my-project',
        requested_zones=set(['zone-1']),
        filter_expr=None,
        http=self.mock_http(),
        batch_url=self.batch_url,
        errors=[])

    self.list_json.assert_called_once_with(
        requests=[(self.compute.instanceGroupManagers,
                   'List',
                   self.messages.ComputeInstanceGroupManagersListRequest(
                       project='my-project',
                       zone='zone-1')),
                  (self.compute.instanceGroupManagers,
                   'List',
                   self.messages.ComputeInstanceGroupManagersListRequest(
                       project='my-project',
                       zone='zone-2'))],
        http=self.mock_http(),
        batch_url=self.batch_url,
        errors=[])

    self.CheckRequests(
        [(self.compute.autoscalers,
          'List',
          self.messages.ComputeAutoscalersListRequest(
              maxResults=500,
              project='my-project',
              zone='zone-1'))
        ],
    )

    self.AssertOutputEquals(
        textwrap.dedent("""\
        NAME    LOCATION SCOPE  BASE_INSTANCE_NAME   SIZE TARGET_SIZE INSTANCE_TEMPLATE AUTOSCALED
        group-1 zone-1   zone   test-instance-name-1 0    1           template-1        yes
        group-2 zone-1   zone   test-instance-name-2 3    10          template-2        no
        group-3 zone-1   zone   test-instance-name-3 10   1           template-2        no
        """), normalize_space=True)
    self.AssertErrEquals("""\
    WARNING: Flag `--zones` is deprecated. Use `--filter="zone:( ZONE ... )"` instead.
    For example `--filter="zone:( europe-west1-b europe-west1-c )"`.
    """, normalize_space=True)
Exemplo n.º 9
0
  def testDescribeAutoscaledRegional(self):
    self.mock_client.regionInstanceGroupManagers.Get.Expect(
        messages.ComputeRegionInstanceGroupManagersGetRequest(
            instanceGroupManager='group-1',
            project='fake-project',
            region='region-1'),
        test_resources.MakeInstanceGroupManagers(
            API_VERSION, scope_type='region', scope_name='region-1')[0]
    )
    self._MockAutoscalerRequest(test_resources.MakeAutoscalers(
        API_VERSION, scope_name='region-1', scope_type='region'))
    self.Run("""
        compute instance-groups managed describe group-1 --region region-1
        """)

    self.assertMultiLineEqual(
        encoding.Decode(self.stdout.getvalue()),
        textwrap.dedent("""\
            autoscaler:
              autoscalingPolicy:
                coolDownPeriodSec: 60
                cpuUtilization:
                  utilizationTarget: 0.8
                customMetricUtilizations:
                - metric: custom.cloudmonitoring.googleapis.com/seconds
                  utilizationTarget: 60.0
                  utilizationTargetType: DELTA_PER_MINUTE
                loadBalancingUtilization:
                  utilizationTarget: 0.9
                maxNumReplicas: 10
                minNumReplicas: 2
              creationTimestamp: Two days ago
              id: '1'
              name: autoscaler-1
              region: {0}/projects/my-project/regions/region-1
              selfLink: {0}/projects/my-project/regions/region-1/autoscalers/autoscaler-1
              target: {0}/projects/my-project/regions/region-1/instanceGroupManagers/group-1
            baseInstanceName: test-instance-name-1
            creationTimestamp: '2013-09-06T17:54:10.636-07:00'
            description: Test description.
            fingerprint: MTIzNA==
            instanceGroup: {0}/projects/my-project/regions/region-1/instanceGroups/group-1
            instanceTemplate: {0}/projects/my-project/global/instanceTemplates/template-1
            name: group-1
            region: {0}/projects/my-project/regions/region-1
            selfLink: {0}/projects/my-project/regions/region-1/instanceGroupManagers/group-1
            targetSize: 1
            """.format(self.compute_uri)))
Exemplo n.º 10
0
 def _SetUpRegional(self, api_version):
     self.SelectApi(api_version)
     self.region = 'us-central2'
     self.scope_params = ('region', self.region)
     self.make_requests.side_effect = iter([
         [
             test_resources.MakeInstanceGroupManagers(
                 api_version, scope_name=self.region,
                 scope_type='region')[0],
         ],
         [
             test_resources.MakeInstanceGroups(self.messages,
                                               api_version,
                                               scope_name=self.region,
                                               scope_type='region')[0],
         ],
         [
             test_resources.MakeAutoscalers(api_version,
                                            scope_name=self.region,
                                            scope_type='region')[0],
         ],
     ])
     self.region_ig_list_request = [
         (self.compute.regionInstanceGroups, 'List',
          self.messages.ComputeRegionInstanceGroupsListRequest(
              maxResults=500,
              project='my-project',
              region=self.region,
          ))
     ]
     self.region_as_list_request = [
         (self.compute.regionAutoscalers, 'List',
          self.messages.ComputeRegionAutoscalersListRequest(
              maxResults=500, project='my-project', region=self.region))
     ]
     self.template_1_uri = (
         '{0}/projects/my-project/global/instanceTemplates/template-1'.
         format(self.compute_uri))
     self.http_health_check_uri = (
         '{0}/projects/my-project/global/httpHealthChecks/health-check-1'.
         format(self.compute_uri))
     self.https_health_check_uri = (
         '{0}/projects/my-project/global/httpsHealthChecks/health-check-2'.
         format(self.compute_uri))
     self.region_uri = ('{0}/projects/my-project/regions/{1}'.format(
         self.compute_uri, self.region))
Exemplo n.º 11
0
    def testScopePrompting(self):
        self.StartPatch('googlecloudsdk.core.console.console_io.CanPrompt',
                        return_value=True)
        self.make_requests.side_effect = iter([
            [self.messages.Region(name='region-1')],
            [
                self.messages.Zone(name='zone-2'),
                self.messages.Zone(name='zone-1')
            ],
            test_resources.MakeAutoscalers(API_VERSION),
            test_resources.MakeInstanceGroupManagers(API_VERSION),
            [],  # Deleting 0 Autoscalers.
        ])
        self.WriteInput('2\ny')
        self.Run("""
        compute instance-groups managed delete group-1 group-2
        """)

        self.CheckRequests(
            self.regions_list_request,
            self.zones_list_request,
            self.autoscalers_list_request_zone_1,
            [(self.compute.autoscalers, 'Delete',
              self.messages.ComputeAutoscalersDeleteRequest(
                  autoscaler='autoscaler-1',
                  project='my-project',
                  zone='zone-1')),
             (self.compute.autoscalers, 'Delete',
              self.messages.ComputeAutoscalersDeleteRequest(
                  autoscaler='autoscaler-2',
                  project='my-project',
                  zone='zone-1'))],
            [(self.compute.instanceGroupManagers, 'Delete',
              self.messages.ComputeInstanceGroupManagersDeleteRequest(
                  instanceGroupManager='group-1',
                  project='my-project',
                  zone='zone-1')),
             (self.compute.instanceGroupManagers, 'Delete',
              self.messages.ComputeInstanceGroupManagersDeleteRequest(
                  instanceGroupManager='group-2',
                  project='my-project',
                  zone='zone-1'))],
        )
Exemplo n.º 12
0
class InstanceGroupManagersSetAutoscalingZonalTest(test_base.BaseTest):

  INSTANCE_GROUP_MANAGERS = (
      test_resources.MakeInstanceGroupManagers(API_VERSION))
  AUTOSCALERS = test_resources.MakeAutoscalers(API_VERSION)

  def SetUp(self):
    self.SelectApi(API_VERSION)
    self.track = calliope_base.ReleaseTrack.ALPHA
    self.make_requests.side_effect = iter([
        [self.INSTANCE_GROUP_MANAGERS[0]],  # Get IGM.
        self.AUTOSCALERS[1:],
        []  # Insert autoscaler.
    ])

    self.StartObjectPatch(random, 'choice').return_value = 'a'
    self.autoscalers_list_request = [
        (
            self.compute.autoscalers,
            'List', self.messages.ComputeAutoscalersListRequest(
                maxResults=500,
                project='my-project',
                zone='zone-1',
            ),
        ),
    ]
    self.managed_instance_group_get_request = [
        (
            self.compute.instanceGroupManagers,
            'Get', self.messages.ComputeInstanceGroupManagersGetRequest(
                instanceGroupManager='group-1',
                project='my-project',
                zone='zone-1',
            ),
        )
    ]
    self.managed_instance_group_self_link = (
        '{0}/projects/my-project/zones/zone-1/instanceGroupManagers/group-1'
        .format(self.compute_uri)
    )

  def testInsertMinimalAutoscaler(self):
    self.Run('compute instance-groups managed set-autoscaling group-1 '
             '--max-num-replicas 10 --zone zone-1')
    request = self.messages.ComputeAutoscalersInsertRequest(
        autoscaler=self.messages.Autoscaler(
            autoscalingPolicy=self.messages.AutoscalingPolicy(
                customMetricUtilizations=[],
                maxNumReplicas=10,
            ),
            name='group-1-aaaa',
            target=self.managed_instance_group_self_link,
        ),
        project='my-project',
        zone='zone-1',
    )
    self.CheckRequests(
        self.managed_instance_group_get_request,
        self.autoscalers_list_request,
        [(self.compute.autoscalers, 'Insert', request)],
    )

  def testUpdateMinimalAutoscalerWithScopePrompt(self):
    self.StartPatch('googlecloudsdk.core.console.console_io.CanPrompt',
                    return_value=True)
    self.WriteInput('2\n')
    self.make_requests.side_effect = iter([
        [self.messages.Region(name='region-1')],
        [self.messages.Zone(name='zone-1'), self.messages.Zone(name='zone-2')],
        [self.INSTANCE_GROUP_MANAGERS[0]],
        self.AUTOSCALERS,
        []
    ])

    self.Run('compute instance-groups managed set-autoscaling group-1 '
             '--max-num-replicas 10')

    request = self.messages.ComputeAutoscalersUpdateRequest(
        autoscaler='autoscaler-1',
        autoscalerResource=self.messages.Autoscaler(
            autoscalingPolicy=self.messages.AutoscalingPolicy(
                customMetricUtilizations=[
                    self.messages.AutoscalingPolicyCustomMetricUtilization(
                        metric='custom.cloudmonitoring.googleapis.com/seconds',
                        utilizationTarget=60.0,
                        utilizationTargetType=_GetUtilizationTargetType(
                            self.messages, 'DELTA_PER_MINUTE'),
                    )
                ],
                maxNumReplicas=10,
            ),
            name='autoscaler-1',
            target=self.managed_instance_group_self_link,
        ),
        project='my-project',
        zone='zone-1',
    )
    self.CheckRequests(
        self.regions_list_request,
        self.zones_list_request,
        self.managed_instance_group_get_request,
        self.autoscalers_list_request,
        [(self.compute.autoscalers, 'Update', request)],
    )

  def testInsertAutoscalerWithEverything(self):
    self.Run('compute instance-groups managed set-autoscaling group-1 '
             '--max-num-replicas 10 '
             '--zone zone-1 '
             '--cool-down-period 1m '
             '--description whatever '
             '--min-num-replicas 5 '
             '--max-num-replicas 10 '
             '--scale-based-on-cpu --target-cpu-utilization 0.5 '
             '--scale-based-on-load-balancing '
             '--target-load-balancing-utilization 0.8 '
             '--custom-metric-utilization metric=metric1,utilization-target=1,'
             'utilization-target-type=GAUGE '
             '--custom-metric-utilization metric=metric2,utilization-target=2,'
             'utilization-target-type=DELTA_PER_SECOND '
             '--custom-metric-utilization metric=metric3,utilization-target=3,'
             'utilization-target-type=DELTA_PER_MINUTE '
            )
    request = self.messages.ComputeAutoscalersInsertRequest(
        autoscaler=self.messages.Autoscaler(
            autoscalingPolicy=self.messages.AutoscalingPolicy(
                cpuUtilization=self.messages.AutoscalingPolicyCpuUtilization(
                    utilizationTarget=0.5,
                ),
                customMetricUtilizations=[
                    self.messages.AutoscalingPolicyCustomMetricUtilization(
                        metric='metric1',
                        utilizationTarget=1.0,
                        utilizationTargetType=_GetUtilizationTargetType(
                            self.messages, 'GAUGE'),
                    ),
                    self.messages.AutoscalingPolicyCustomMetricUtilization(
                        metric='metric2',
                        utilizationTarget=2.0,
                        utilizationTargetType=_GetUtilizationTargetType(
                            self.messages, 'DELTA_PER_SECOND'),
                    ),
                    self.messages.AutoscalingPolicyCustomMetricUtilization(
                        metric='metric3',
                        utilizationTarget=3.0,
                        utilizationTargetType=_GetUtilizationTargetType(
                            self.messages, 'DELTA_PER_MINUTE'),
                    ),
                ],
                loadBalancingUtilization=(
                    self.messages.AutoscalingPolicyLoadBalancingUtilization)(
                        utilizationTarget=0.8,
                    ),
                maxNumReplicas=10,
                minNumReplicas=5,
                coolDownPeriodSec=60,
            ),
            description='whatever',
            name='group-1-aaaa',
            target=self.managed_instance_group_self_link,
        ),
        project='my-project',
        zone='zone-1',
    )
    self.CheckRequests(
        self.managed_instance_group_get_request,
        self.autoscalers_list_request,
        [(self.compute.autoscalers, 'Insert', request)],
    )

  def testAssertsIgmExists(self):
    def MakeRequests(*_, **kwargs):
      kwargs['errors'].append((404, 'Not Found'))
      yield
    self.make_requests.side_effect = MakeRequests

    with self.assertRaisesRegex(
        managed_instance_groups_utils.ResourceNotFoundException,
        'Could not fetch resource:'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1')

    self.CheckRequests(self.managed_instance_group_get_request)

  def testAssertsPositiveMinSize(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --min-num-replicas: Value must be greater than or equal to '
        r'0; received: -1'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--min-num-replicas -1')

  def testAssertsPositiveMaxSize(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --max-num-replicas: Value must be greater than or equal to '
        r'0; received: -1'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas -10 --zone zone-1')

  def testAssertsMaxSizeGreaterThanMinSize(self):
    with self.assertRaisesRegex(
        exceptions.InvalidArgumentException,
        r'Invalid value for \[--max-num-replicas\]: can\'t be less than min '
        r'num replicas\.'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--min-num-replicas 11')

  def testAssertsCpuTargetIsPositive(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --target-cpu-utilization: '
        r'Value must be greater than or equal to 0.0; received: -0.1\d*'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--target-cpu-utilization -0.11')

  def testAssertsCpuTargetNotAboveOne(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --target-cpu-utilization: '
        r'Value must be less than or equal to 1.0; received: 1.1\d*'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--target-cpu-utilization 1.1')

  def testAssertsCustomMetricSpecificationComplete(self):
    with self.assertRaisesRegex(
        exceptions.InvalidArgumentException,
        r'Invalid value for \[--custom-metric-utilization\]: metric not '
        r'present\.'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--custom-metric-utilization utilization-target=1,'
               'utilization-target-type=GAUGE')

  def testAssertsCustomMetricTargetPositive(self):
    with self.assertRaisesRegex(
        exceptions.InvalidArgumentException,
        r'Invalid value for '
        r'\[--custom-metric-utilization utilization-target\]: less than 0\.'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--custom-metric-utilization utilization-target=-1,'
               'utilization-target-type=GAUGE,metric=metric')

  def testAssertsLbTargetPositive(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --target-load-balancing-utilization: '
        r'Value must be greater than or equal to 0.0; received: -0.1\d*'):
      self.Run('compute instance-groups managed set-autoscaling group-1 '
               '--max-num-replicas 10 --zone zone-1 '
               '--target-load-balancing-utilization -0.11')
class InstanceGroupManagersStopAutoscalingZonalTest(test_base.BaseTest):

    INSTANCE_GROUP_MANAGERS = test_resources.MakeInstanceGroupManagers(
        api=API_VERSION)
    AUTOSCALERS = test_resources.MakeAutoscalers(api=API_VERSION)

    def SetUp(self):
        self.SelectApi(API_VERSION)
        self.autoscalers_list_request = [
            (
                self.compute.autoscalers,
                'List',
                self.messages.ComputeAutoscalersListRequest(
                    maxResults=500,
                    project='my-project',
                    zone='zone-1',
                ),
            ),
        ]
        self.managed_instance_group_get_request = [(
            self.compute.instanceGroupManagers,
            'Get',
            self.messages.ComputeInstanceGroupManagersGetRequest(
                instanceGroupManager='group-1',
                project='my-project',
                zone='zone-1',
            ),
        )]

    def testStopAutoscalingNotAutoscaledManagedInstanceGroup(self):
        self.make_requests.side_effect = iter([
            [self.INSTANCE_GROUP_MANAGERS[0]],
            self.AUTOSCALERS[1:],
        ])

        with self.assertRaisesRegex(
                managed_instance_groups_utils.ResourceNotFoundException,
                r'The managed instance group is not autoscaled\.'):
            self.Run(
                'compute instance-groups managed stop-autoscaling group-1 '
                '--zone zone-1')
        self.CheckRequests(self.managed_instance_group_get_request,
                           self.autoscalers_list_request)

    def testStopAutoscalingAutoscaledManagedInstanceGroupWithPrompt(self):
        self.StartPatch('googlecloudsdk.core.console.console_io.CanPrompt',
                        return_value=True)
        self.WriteInput('2\n')
        self.make_requests.side_effect = iter([
            [self.messages.Region(name='region-1')],
            [
                self.messages.Zone(name='zone-1'),
                self.messages.Zone(name='zone-2')
            ],
            [self.INSTANCE_GROUP_MANAGERS[0]],
            self.AUTOSCALERS,
            []  # Delete Autoscaler.
        ])

        self.Run('compute instance-groups managed stop-autoscaling group-1')
        delete_request = self.messages.ComputeAutoscalersDeleteRequest(
            project='my-project', zone='zone-1', autoscaler='autoscaler-1')
        self.CheckRequests(
            self.regions_list_request,
            self.zones_list_request,
            self.managed_instance_group_get_request,
            self.autoscalers_list_request,
            [(self.compute.autoscalers, 'Delete', delete_request)],
        )

    def testAssertsIgmExists(self):
        def MakeRequests(*_, **kwargs):
            kwargs['errors'].append((404, 'Not Found'))
            yield

        self.make_requests.side_effect = MakeRequests

        with self.assertRaisesRegex(
                managed_instance_groups_utils.ResourceNotFoundException,
                'Could not fetch resource:'):
            self.Run(
                'compute instance-groups managed stop-autoscaling group-1 '
                '--zone zone-1')

        self.CheckRequests(self.managed_instance_group_get_request)