def _GetExistingResource(self, args):
        get_method = registry.GetMethod(self.spec.request.collection, 'get',
                                        self.spec.request.api_version)
        get_arg_generator = arg_marshalling.DeclarativeArgumentGenerator(
            get_method, [], self.spec.arguments.resource)

        # TODO(b/111069150): Add error handling when get fails.
        return get_method.Call(get_arg_generator.CreateRequest(args))
Example #2
0
 def testGenerateAtomicListRaw(self):
     self.MockCRUDMethods(('foo.projects.instances', True))
     method = registry.GetMethod('foo.projects.instances', 'list')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=True)
     (_, args) = CheckArgs(gen.GenerateArgs())
     self.assertEqual([
         '--pageSize', '--pageToken', '--parent', '--projectsId', 'resource'
     ], sorted(args.keys()))
 def testDescribe(self):
     self.MockAPI('compute', 'v1')
     request = self.messages.ComputeInstancesGetRequest(
         instance='testinstance', zone='zone1', project='foo')
     self.mocked_client.instances.Get.Expect(request,
                                             response={'foo': 'bar'},
                                             enable_type_checking=False)
     registry.GetMethod('compute.instances', 'get').Call(request)
Example #4
0
 def PatchBookResourceReturnTypes(self):
     """Patch each resource method to have certain return type messages."""
     self._PatchProjectReturnType()
     shelves_method = registry.GetMethod('example.projects.shelves', 'list')
     self.StartObjectPatch(shelves_method,
                           'GetResponseType',
                           return_value=ShelvesMessage)
     self._PatchBookReturnType()
 def __init__(self, **kwargs):
   super(ProjectCompleter, self).__init__(
       resource_spec,
       project_collection,
       registry.GetMethod('cloudresourcemanager.projects', 'list'),
       param='projectsId',
       static_params=static_params,
       id_field=id_field,
       **kwargs)
Example #6
0
 def testParseResourceIntoMessageCreateWithParentResource(self):
   self.MockCRUDMethods(('foo.projects.locations.instances', True))
   method = registry.GetMethod('foo.projects.locations.instances', 'create')
   message = method.GetRequestType()()
   parent_ref = resources.REGISTRY.Parse(
       'projects/p/locations/l',
       collection='foo.projects.locations')
   arg_utils.ParseResourceIntoMessage(parent_ref, method, message)
   self.assertEqual('projects/p/locations/l', message.parent)
Example #7
0
 def testGenerateFlatList(self):
     self.MockCRUDMethods(('foo.projects.instances', False))
     method = registry.GetMethod('foo.projects.instances', 'list')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=False)
     (_, args) = CheckArgs(gen.GenerateArgs())
     self.assertEqual([
         '--filter', '--limit', '--page-size', '--projectsId', '--sort-by',
         'resource'
     ], sorted(args.keys()))
Example #8
0
 def __init__(self, spec):
     self.spec = spec
     self.method = registry.GetMethod(self.spec.request.collection,
                                      self.spec.request.method,
                                      self.spec.request.api_version)
     resource_arg = self.spec.arguments.resource
     self.arg_generator = arg_marshalling.DeclarativeArgumentGenerator(
         self.method, self.spec.arguments.params, resource_arg)
     self.resource_type = resource_arg.name if resource_arg else None
 def __init__(self, **kwargs):
   super(BookCompleter, self).__init__(
       resource_spec,
       book_collection,
       registry.GetMethod('example.projects.shelves.books', 'list'),
       param='booksId',
       static_params=static_params,
       id_field=id_field,
       **kwargs)
    def _CommonRun(self, args, existing_message=None):
        """Performs run actions common to all commands.

    Parses the resource argument into a resource reference
    Prompts the user to continue (if applicable)
    Calls the API method with the request generated from the parsed arguments

    Args:
      args: The argparse parser.
      existing_message: the apitools message returned from previous request.

    Returns:
      (resources.Resource, response), A tuple of the parsed resource reference
      and the API response from the method call.
    """
        ref = self.arg_generator.GetRequestResourceRef(args)
        if self.spec.input.confirmation_prompt:
            console_io.PromptContinue(self._Format(
                self.spec.input.confirmation_prompt, ref,
                self._GetDisplayName(ref, args)),
                                      throw_if_unattended=True,
                                      cancel_on_no=True)

        if self.spec.request.modify_method_hook:
            self.spec.request.method = self.spec.request.modify_method_hook(
                ref, args)
            self.method = registry.GetMethod(self.spec.request.collection,
                                             self.spec.request.method,
                                             self.spec.request.api_version)

        if self.spec.request.issue_request_hook:
            # Making the request is overridden, just call into the custom code.
            return ref, self.spec.request.issue_request_hook(ref, args)

        if self.spec.request.create_request_hook:
            # We are going to make the request, but there is custom code to create it.
            request = self.spec.request.create_request_hook(ref, args)
        else:
            parse_resource = self.spec.request.parse_resource_into_request
            request = self.arg_generator.CreateRequest(
                args,
                self.spec.request.static_fields,
                self.spec.request.resource_method_params,
                self.spec.arguments.labels,
                self.spec.command_type,
                use_relative_name=self.spec.request.use_relative_name,
                parse_resource_into_request=parse_resource,
                existing_message=existing_message,
                override_method=self.method)
            for hook in self.spec.request.modify_request_hooks:
                request = hook(ref, args, request)

        response = self.method.Call(
            request,
            limit=self.arg_generator.Limit(args),
            page_size=self.arg_generator.PageSize(args))
        return ref, response
 def _GetIamPolicy(self, args):
     get_iam_method = registry.GetMethod(self.spec.request.collection,
                                         'getIamPolicy',
                                         self.spec.request.api_version)
     get_iam_request = self.arg_generator.CreateRequest(
         args,
         use_relative_name=self.spec.request.use_relative_name,
         override_method=get_iam_method)
     policy = get_iam_method.Call(get_iam_request)
     return policy
Example #12
0
 def testDescribe(self):
     self.MockAPI('compute', 'v1')
     request = self.messages.ComputeInstancesGetRequest(
         instance='testinstance', zone='zone1', project='foo')
     self.mocked_client.instances.Get.Expect(request,
                                             response={'foo': 'bar'},
                                             enable_type_checking=False)
     registry.GetMethod('compute.instances', 'get').Call(request)
     self.mocked_http.assert_called_once_with(
         response_encoding=http.ENCODING, use_google_auth=False)
  def testCompleterForAttribute_DifferentVersions(self):
    collections = [
        ('example.projects.shelves.books', True),
        ('example.projects.shelves', True),
        ('example.projects', True),
        ('example.projects.shelves.books', True, 'v1beta1'),
        ('example.projects.shelves', True, 'v1beta1'),
        ('example.projects', True, 'v1beta1')]
    self.MockCRUDMethods(*collections)
    book_collection = registry.GetAPICollection(
        'example.projects.shelves.books', 'v1beta1')
    resource_spec = util.GetBookResource(api_version='v1beta1')

    expected_completer = completers.ResourceArgumentCompleter(
        resource_spec,
        book_collection,
        registry.GetMethod('example.projects.shelves.books', 'list',
                           api_version='v1beta1'),
        param='booksId',
        static_params={})
    completer = completers.CompleterForAttribute(self.resource_spec, 'book')()

    self.assertEqual(expected_completer, completer)
    expected_completer = completers.ResourceArgumentCompleter(
        resource_spec,
        registry.GetAPICollection('example.projects.shelves', 'v1beta1'),
        registry.GetMethod('example.projects.shelves', 'list',
                           api_version='v1beta1'),
        param='shelvesId',
        static_params={})
    completer = completers.CompleterForAttribute(self.resource_spec, 'shelf')()
    self.assertEqual(expected_completer, completer)

    expected_completer = completers.ResourceArgumentCompleter(
        self.resource_spec,
        registry.GetAPICollection('example.projects', 'v1beta1'),
        registry.GetMethod('example.projects', 'list', api_version='v1beta1'),
        param='projectsId',
        static_params={})
    completer = completers.CompleterForAttribute(
        self.resource_spec, 'project')()
    self.assertEqual(expected_completer, completer)
Example #14
0
 def __init__(self, spec):
     self.spec = spec
     self.method = registry.GetMethod(self.spec.request.collection,
                                      self.spec.request.method,
                                      self.spec.request.api_version)
     resource_args = (self.spec.arguments.resource.params
                      if self.spec.arguments.resource else [])
     self.arg_generator = arg_marshalling.DeclarativeArgumentGenerator(
         self.method, self.spec.arguments.params +
         self.spec.arguments.mutex_group_params, resource_args)
     self.resource_type = self.arg_generator.resource_arg_name
 def __init__(self, spec):
     self.spec = spec
     self.method = registry.GetMethod(self.spec.request.collection,
                                      self.spec.request.method,
                                      self.spec.request.api_version)
     self.arg_generator = arg_marshalling.ArgumentGenerator(
         self.method,
         self.spec.arguments.AllArguments(),
         builtin_args=CommandBuilder.IGNORED_FLAGS,
         clean_surface=True)
     self.resource_type = self.arg_generator.resource_arg_name
Example #16
0
 def testParseResourceIntoMessageList(self):
   self.MockCRUDMethods(('foo.projects.locations.instances', True))
   method = registry.GetMethod('foo.projects.locations.instances', 'list')
   message = method.GetRequestType()()
   ref = resources.REGISTRY.Parse(
       'projects/p/locations/l',
       collection=method.request_collection.full_name)
   arg_utils.ParseResourceIntoMessage(
       ref,
       method,
       message)
   self.assertEqual('projects/p/locations/l', message.parent)
Example #17
0
 def testCreateFlatGet(self, raw, data):
     resource, projects_id, prop, instances_id = data
     properties.VALUES.core.project.Set(prop)
     self.MockCRUDMethods(('foo.projects.instances', False))
     method = registry.GetMethod('foo.projects.instances', 'get')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=raw)
     mock_request_type = method.GetRequestType()
     gen.CreateRequest(
         mock.MagicMock(resource=resource,
                        projectsId=projects_id,
                        instancesId=instances_id))
     mock_request_type.assert_called_once_with(instancesId='i',
                                               projectsId='p')
Example #18
0
 def testCreateFlatList(self, resource, projects_id, prop, filter_arg,
                        sort_by, result):
     properties.VALUES.core.project.Set(prop)
     self.MockCRUDMethods(('foo.projects.instances', False))
     method = registry.GetMethod('foo.projects.instances', 'list')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=False)
     mock_request_type = method.GetRequestType()
     gen.CreateRequest(
         mock.MagicMock(resource=resource,
                        projectsId=projects_id,
                        filter=filter_arg,
                        sort_by=sort_by))
     mock_request_type.assert_called_once_with(**result)
 def __init__(self, spec, path):
     self.spec = spec
     self.path = path
     self.method = registry.GetMethod(self.spec.request.collection,
                                      self.spec.request.method,
                                      self.spec.request.api_version)
     resource_arg = self.spec.arguments.resource
     self.arg_generator = arg_marshalling.DeclarativeArgumentGenerator(
         self.method, self.spec.arguments.params, resource_arg)
     self.display_resource_type = self.spec.request.display_resource_type
     if (not self.display_resource_type and resource_arg
             and not resource_arg.is_parent_resource):
         self.display_resource_type = resource_arg.name if resource_arg else None
  def testCollectionOverride(self):
    self.MockCRUDMethods(('foo.projects.instances', True),
                         ('bar.instances', True))
    method = registry.GetMethod('foo.projects.instances', 'get')

    r = resource_arg_schema.YAMLResourceArgument(
        {'name': 'instance', 'collection': 'bar.instances',
         'attributes': [
             {'parameter_name': 'instancesId', 'attribute_name': 'instance',
              'help': 'h'}]},
        group_help='group_help', override_resource_collection=True)

    r.GenerateResourceSpec(method.collection)
Example #21
0
 def __init__(self, spec):
     self.spec = spec
     self.method = registry.GetMethod(self.spec.request.collection,
                                      self.spec.request.method,
                                      self.spec.request.api_version)
     arg_info = dict(self.spec.message_params)
     arg_info.update(self.spec.resource_arg.request_params)
     self.arg_generator = arg_marshalling.ArgumentGenerator(
         self.method,
         arg_info,
         builtin_args=CommandBuilder.IGNORED_FLAGS,
         clean_surface=True)
     self.resource_type = self.arg_generator.resource_arg_name
Example #22
0
 def testResponseRef(self, is_atomic):
     self.MockCRUDMethods(('foo.projects.instances', is_atomic))
     method = registry.GetMethod('foo.projects.instances', 'list')
     gen = arg_marshalling.DeclarativeArgumentGenerator(
         method, [], MakeResource(collection='foo.projects', attributes=[]))
     (parser, args) = CheckArgs(gen.GenerateArgs())
     self.assertEqual([], sorted(args.keys()))
     # Test parsing the response reference.
     properties.VALUES.core.project.Set('p')
     namespace = parser.parse_args([])
     ref = gen.GetResponseResourceRef('foo', namespace)
     self.assertEqual(ref.instancesId, 'foo')
     self.assertEqual(ref.projectsId, 'p')
     self.assertEqual(ref.Collection(), 'foo.projects.instances')
Example #23
0
 def testCreateAtomicGet(self, raw, data):
     resource, projects_id, prop, instances_id, name = data
     properties.VALUES.core.project.Set(prop)
     self.MockCRUDMethods(('foo.projects.instances', True))
     method = registry.GetMethod('foo.projects.instances', 'get')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=raw)
     mock_request_type = method.GetRequestType()
     m = mock.MagicMock(resource=resource,
                        projectsId=projects_id,
                        instancesId=instances_id)
     m.name = name
     gen.CreateRequest(m)
     mock_request_type.assert_called_once_with(
         name='projects/p/instances/i')
Example #24
0
 def testCreateAtomicListRaw(self, resource, parent, projects_id, prop,
                             page_token, page_size, result):
     properties.VALUES.core.project.Set(prop)
     self.MockCRUDMethods(('foo.projects.instances', True))
     method = registry.GetMethod('foo.projects.instances', 'list')
     gen = arg_marshalling.AutoArgumentGenerator(method, raw=True)
     mock_request_type = method.GetRequestType()
     m = mock.MagicMock(resource=resource,
                        projectsId=projects_id,
                        pageToken=page_token,
                        pageSize=page_size)
     m.parent = parent
     gen.CreateRequest(m)
     mock_request_type.assert_called_once_with(**result)
 def testRawListNoPageSize(self):
     self.MockAPI('bigtableadmin', 'v2')
     request = self.messages.BigtableadminProjectsInstancesListRequest(
         parent='foo', pageToken=None)
     response = self.messages.ListInstancesResponse(instances=[
         self.messages.Instance(name='instance-1'),
         self.messages.Instance(name='instance-2')
     ])
     self.mocked_client.projects_instances.List.Expect(request, response)
     actual = registry.GetMethod('bigtableadmin.projects.instances',
                                 'list').Call(request, raw=True)
     self.assertEqual(len(actual.instances), 2)
     self.assertEqual(actual.instances[0].name, 'instance-1')
     self.assertEqual(actual.instances[1].name, 'instance-2')
def _GetCollectionAndMethod(resource_spec, attribute_name):
  # type: (concepts.ResourceSpec, str) -> typing.Tuple[typing.Optional[dict], typing.Optional[str], typing.Optional[resource_lib.CollectionInfo], typing.Optional[registry.APIMethod]]  # pylint: disable=line-too-long
  """Gets static params, name, collection, method of attribute in resource."""
  for a in resource_spec.attributes:
    if a.name == attribute_name:
      attribute = a
      break
  else:
    raise AttributeError(
        'Attribute [{}] not found in resource.'.format(attribute_name))
  static_params = attribute.completion_request_params
  id_field = attribute.completion_id_field
  collection_info = _GetCompleterCollectionInfo(resource_spec, attribute)
  if not collection_info:
    return static_params, id_field, None, None
  # If there is no appropriate list method for the collection, we can't auto-
  # create a completer.
  try:
    method = registry.GetMethod(
        collection_info.full_name, 'list',
        api_version=collection_info.api_version)
  except registry.UnknownMethodError:
    if (collection_info.full_name != _PROJECTS_COLLECTION
        and collection_info.full_name.split('.')[-1] == 'projects'):
      # The CloudResourceManager projects methods can be used for "synthetic"
      # project resources that don't have their own method.
      # This is a bit of a hack, so if any resource arguments come up for
      # which this doesn't work, a toggle should be added to the
      # ResourceSpec class to disable this.
      method = registry.GetMethod(_PROJECTS_COLLECTION, 'list')
      static_params = _PROJECTS_STATIC_PARAMS
      id_field = _PROJECTS_ID_FIELD
    else:
      method = None
  except registry.Error:
    method = None
  return static_params, id_field, collection_info, method
 def testRawListNonPageable(self):
     self.MockAPI('container', 'v1')
     request = self.messages.ContainerProjectsLocationsClustersListRequest(
         parent='projects/foo/locations/zone1')
     response = self.messages.ListClustersResponse(clusters=[
         self.messages.Cluster(name='c-1'),
         self.messages.Cluster(name='c-2')
     ])
     self.mocked_client.projects_locations_clusters.List.Expect(
         request, response)
     actual = registry.GetMethod('container.projects.locations.clusters',
                                 'list').Call(request, raw=True)
     self.assertEqual(len(actual.clusters), 2)
     self.assertEqual(actual.clusters[0].name, 'c-1')
     self.assertEqual(actual.clusters[1].name, 'c-2')
  def testWithParentResource(self):
    self.MockCRUDMethods(('foo.projects.instances', False))
    method = registry.GetMethod('foo.projects.instances', 'create')

    r = resource_arg_schema.YAMLResourceArgument(
        {
            'name': 'instance',
            'collection': 'foo.projects',
            'attributes': [
                {'parameter_name': 'projectsId', 'attribute_name': 'project',
                 'help': 'h'}],
        },
        group_help='group_help', is_parent_resource=True)

    r.GenerateResourceSpec(method.resource_argument_collection)
Example #29
0
 def testParseResourceIntoMessageCreate(self):
   self.MockCRUDMethods(('foo.projects.locations.instances', True))
   method = registry.GetMethod('foo.projects.locations.instances', 'create')
   message = method.GetRequestType()()
   message.field_by_name = mock.MagicMock()
   ref = resources.REGISTRY.Parse(
       'projects/p/locations/l/instances/i',
       collection=method.resource_argument_collection.full_name)
   arg_utils.ParseResourceIntoMessage(
       ref,
       method,
       message,
       request_id_field='name')
   self.assertEqual('projects/p/locations/l', message.parent)
   self.assertEqual('i', message.name)
 def testInsert(self):
     self.MockAPI('compute', 'v1')
     request = self.messages.ComputeInstancesInsertRequest(
         instance=self.messages.Instance(
             name='testinstance',
             networkInterfaces=[
                 self.messages.NetworkInterface(network='network', )
             ],
         ),
         zone='zone1',
         project='foo')
     self.mocked_client.instances.Insert.Expect(request, {})
     self.assertEqual({},
                      registry.GetMethod('compute.instances',
                                         'insert').Call(request))