示例#1
0
def CheckArgs(args):
    parser = calliope_util.ArgumentParser()
    expanded_args = {}

    def _AddArgs(arguments, top=False):
        for arg in arguments:
            if top:
                arg.AddToParser(parser)
            if isinstance(arg, concept_parsers.ConceptParser):
                for spec in arg._specs.values():
                    expanded_args.update({
                        a.name: a
                        for a in arg.GetInfo(spec.name).GetAttributeArgs()
                    })
            elif isinstance(arg, calliope_base.ArgumentGroup):
                _AddArgs(arg.arguments)
            else:
                expanded_args[arg.name] = arg

    _AddArgs(args, top=True)

    # Just to make testing easier, since this flag is not actually generated by
    # commands because it exists at the global level.
    parser.add_argument('--project', help='Auxilio aliis.')

    return parser, expanded_args
示例#2
0
 def SetUp(self):
     self.parser = util.ArgumentParser()
     repeated.AddPrimitiveArgs(self.parser,
                               'foo',
                               'bars',
                               'bars',
                               additional_help='Helps you bar.')
 def SetUp(self):
     self.parser = util.ArgumentParser()
     self.parser.add_argument('--cpu', type=int, help='Auxilio aliis.')
     self.parser.add_argument('--memory',
                              type=arg_parsers.BinarySize(),
                              help='Auxilio aliis.')
     self.parser.add_argument('--tier', '-t', help='Auxilio aliis.')
示例#4
0
    def SetUp(self):
        self.parser = util.ArgumentParser()
        properties.VALUES.core.project.Set(_DEFAULT_PROJECT)
        properties.VALUES.privateca.location.Set(_DEFAULT_LOCATION)
        # Child classes can set this to include irrelevant but required args.
        self.other_args = []

        self.mock_client = api_mock.Client(
            privateca_base.GetClientClass(),
            real_client=privateca_base.GetClientInstance())
        self.mock_client.Mock()
        self.addCleanup(self.mock_client.Unmock)

        self.messages = privateca_base.GetMessagesModule()

        self.source_ca = self.messages.CertificateAuthority(
            type=self.messages.CertificateAuthority.TypeValueValuesEnum.
            SELF_SIGNED,
            lifetime='10s',
            config=self.messages.CertificateConfig(
                reusableConfig=self.messages.ReusableConfigWrapper(
                    reusableConfig='my-reusable-config'),
                subjectConfig=self.messages.SubjectConfig(
                    commonName='foobar',
                    subject=self.messages.Subject(organization='foo'))),
            issuingOptions=self.messages.IssuingOptions(),
            keySpec=self.messages.KeyVersionSpec(
                cloudKmsKeyVersion=_KmsKeyVersion()),
            gcsBucket='my-bucket',
        )

        self.request = self.messages.PrivatecaProjectsLocationsCertificateAuthoritiesGetRequest(
            name=_CA_NAME)
示例#5
0
  def testParseBasicTypes(self):
    parser = util.ArgumentParser()
    def Add(field, name):
      a = yaml_command_schema.Argument('asdf', name, 'help')
      arg_utils.GenerateFlag(field, a).AddToParser(parser)

    Add(fm.FakeMessage.string1, 'string1')
    Add(fm.FakeMessage.enum1, 'enum1')
    Add(fm.FakeMessage.bool1, 'bool1')
    Add(fm.FakeMessage.int1, 'int1')
    Add(fm.FakeMessage.float1, 'float1')
    Add(fm.FakeMessage.bytes1, 'bytes1')

    result = parser.parse_args(
        ['--string1', 'foo',
         '--enum1', 'thing-one',
         '--bool1',
         '--int1', '1',
         '--float1', '1.5',
         '--bytes1', "¢συℓ∂η'т ѕαу ησ"])
    self.assertEqual(result.string1, 'foo')
    # Enums don't get converted until arg processing time.
    self.assertEqual(result.enum1, 'thing-one')
    self.assertEqual(result.bool1, True)
    self.assertEqual(result.int1, 1)
    self.assertEqual(result.float1, 1.5)
    self.assertEqual(result.bytes1,
                     b"\xc2\xa2\xcf\x83\xcf\x85\xe2\x84\x93\xe2\x88\x82\xce\xb7"
                     b"'\xd1\x82 \xd1\x95\xce\xb1\xd1\x83 \xce\xb7\xcf\x83")
示例#6
0
    def testHelp(self):
        parser = util.ArgumentParser()
        repeated.AddPrimitiveArgs(parser,
                                  'foo',
                                  'bars',
                                  'bars',
                                  additional_help='Helps you bar.',
                                  is_dict_args=True)

        with self.assertRaises(SystemExit):
            parser.parse_known_args(['--help'])

        self.AssertOutputContains("""\
--update-bars BARS Update the given key-value pairs in the current bars.
 """,
                                  normalize_space=True)
        self.AssertOutputContains('--clear-bars Empty the current bars.',
                                  normalize_space=True)
        self.AssertOutputContains("""\
--remove-bars BARS Remove the key-value pairs from the current bars with
the given keys.
""",
                                  normalize_space=True)
        self.AssertOutputContains("""\
--set-bars BARS Completely replace the current bars with the given key-
value pairs.
""",
                                  normalize_space=True)
示例#7
0
 def testAddArgsForRemoveIamPolicyBindingAddCondition_All(self):
     parser = util.ArgumentParser()
     iam_util.AddArgsForRemoveIamPolicyBinding(parser, add_condition=True)
     res = parser.parse_args(
         ['--role=roles/viewer', '--member=guest', '--all'])
     self.assertEqual(res.role, 'roles/viewer')
     self.assertEqual(res.member, 'guest')
     self.assertEqual(res.all, True)
示例#8
0
 def SetUp(self):
   self.arg_parser = calliope_test_util.ArgumentParser()
   flags.AddVpcConnectorArg(self.arg_parser)
   flags.AddEgressSettingsFlag(self.arg_parser)
   self.can_prompt = self.StartObjectPatch(console_io, 'CanPrompt')
   self.prompt_continue = self.StartObjectPatch(console_io, 'PromptContinue')
   self.service = service.Service.New(self.mock_serverless_client,
                                      self.namespace.namespacesId)
    def testApplyFlagsFile(self,
                           contents,
                           argv,
                           boolean_value,
                           string_value,
                           integer_value,
                           floating_value,
                           kwargs=None):

        if not kwargs:
            kwargs = {}
        expected_argv = kwargs.get('argv')
        exception = kwargs.get('exception')
        exception_regex = kwargs.get('exception_regex')

        parser = calliope_test_util.ArgumentParser()
        cli.FLAG_INTERNAL_FLAG_FILE_LINE.AddToParser(parser)
        parser.add_argument('--boolean',
                            action='store_true',
                            help='Auxilio aliis I.')
        parser.add_argument('--string',
                            default='DEFAULT-FLAG',
                            help='Auxilio aliis II.')
        parser.add_argument('--integer',
                            type=int,
                            default=0,
                            help='Auxilio aliis III.')
        parser.add_argument('--floating',
                            type=float,
                            default=-0.9,
                            help='Auxilio aliis IV.')

        with files.TemporaryDirectory(change_to=True):

            for index, content in enumerate(contents):
                name = 'flags-{}.yaml'.format(index + 1)
                files.WriteFileContents(name, content)

            if not exception:
                argv = cli._ApplyFlagsFile(argv)
                if expected_argv is not None:
                    self.assertEqual(expected_argv, [
                        '{} {}'.format(a.arg, six.text_type(a)) if hasattr(
                            a, 'arg') else a for a in argv
                    ])
                args = parser.parse_args(argv)
                self.assertEqual(boolean_value, args.boolean)
                self.assertEqual(string_value, args.string)
                self.assertEqual(integer_value, args.integer)
                self.assertEqual(floating_value, args.floating)
            elif not exception_regex:
                with self.assertRaises(exception):
                    argv = cli._ApplyFlagsFile(argv)
                    parser.parse_args(argv)
            else:
                with self.assertRaisesRegex(exception, exception_regex):
                    argv = cli._ApplyFlagsFile(argv)
                    parser.parse_args(argv)
示例#10
0
 def testParse(self, args, expected_type):
     self.get_client_instance = self.StartObjectPatch(
         apis, 'GetClientInstance')
     parser = calliope_util.ArgumentParser()
     parser.add_argument('--project', help='The project.')
     util.AddIapIamResourceArgs(parser)
     parsed_args = parser.parse_args(args)
     resource = util.ParseIapIamResource(self.track, parsed_args)
     self.assertEqual(type(resource), expected_type)
示例#11
0
 def SetUp(self):
     self.parser = util.ArgumentParser()
     self.parser.add_argument(
         '--project',
         metavar='PROJECT_ID',
         dest='project',
         help='Google Cloud Platform project ID to use for this invocation.',
         action=actions.StoreProperty(properties.VALUES.core.project))
     self.registry = resources.Registry()
示例#12
0
 def testFallthroughRequiresImplementation(self):
     parser = util.ArgumentParser()
     resource_args.AddSingleResourceArgument(
         parser,
         "organization",
         "The Apigee organization that will test fallback logic.",
         fallthroughs=[BrokenFallthrough()])
     with self.assertRaises(NotImplementedError):
         parser.parse_args([]).CONCEPTS.organization.Parse()
示例#13
0
 def testResourceArgumentValidationUnneeded(self):
     parser = util.ArgumentParser()
     resource_args.AddSingleResourceArgument(
         parser, "organization.developer.app",
         "The application that will test name validation logic.")
     weird_name = "\0invalid/nonsense"
     unparsed_args = ["--organization=oo", "--developer=" + weird_name, "a"]
     args = parser.parse_args(unparsed_args).CONCEPTS.app.Parse()
     self.assertEqual(args.developersId, weird_name)
示例#14
0
 def testParseInvalid(self, args, expected_exception):
     self.get_client_instance = self.StartObjectPatch(
         apis, 'GetClientInstance')
     parser = calliope_util.ArgumentParser()
     parser.add_argument('--project', help='The project.')
     util.AddIapIamResourceArgs(parser)
     with self.assertRaises(expected_exception):
         parsed_args = parser.parse_args(args)
         util.ParseIapIamResource(self.track, parsed_args)
示例#15
0
 def testResourceArgumentValidationFails(self):
     parser = util.ArgumentParser()
     resource_args.AddSingleResourceArgument(
         parser,
         "organization",
         "The Apigee organization that will test name validation logic.",
         validate=True)
     with self.assertRaises(cli_test_base.MockArgumentError):
         parser.parse_args(["invalid*org*name"
                            ]).CONCEPTS.organization.Parse()
 def SetUp(self):
     self.mock_api_adapter = self.StartPatch(
         'googlecloudsdk.api_lib.container.hub.gkehub_api_adapter.APIAdapter'
     )()
     self.mock_kubernetes_client = self.StartPatch(
         'googlecloudsdk.command_lib.container.hub.kube_util.KubernetesClient'
     )()
     self.parser = test_util.ArgumentParser()
     register.Register.Args(self.parser)
     self.registry = resources.Registry()
示例#17
0
 def testResourceArgumentValidationSucceeds(self):
     parser = util.ArgumentParser()
     resource_args.AddSingleResourceArgument(
         parser,
         "organization",
         "The Apigee organization that will test name validation logic.",
         validate=True)
     args = parser.parse_args(["valid-org1-name1"
                               ]).CONCEPTS.organization.Parse()
     self.assertEqual(args.organizationsId, "valid-org1-name1")
示例#18
0
  def SetUp(self):
    action_calls = []

    def custom_validation(value):
      action_calls.append(value)
      return True

    self.parser = util.ArgumentParser()
    self.custom_func = custom_validation
    self.action_calls = action_calls
示例#19
0
 def testResourceArgumentValidationDisabled(self):
     parser = util.ArgumentParser()
     resource_args.AddSingleResourceArgument(
         parser,
         "organization",
         "The Apigee organization that will test name validation logic.",
         validate=False)
     args = parser.parse_args(["invalid*org*name"
                               ]).CONCEPTS.organization.Parse()
     self.assertEqual(args.organizationsId, "invalid*org*name")
示例#20
0
 def SetUp(self):
     self.parser = util.ArgumentParser()
     create.Create.Args(self.parser)
     properties.VALUES.core.project.Set(_DEFAULT_PROJECT)
     properties.VALUES.privateca.location.Set(_DEFAULT_LOCATION)
     self.resource_args = [
         'new-ca', '--kms-key-version',
         'projects/{}/locations/{}/keyRings/kr1/cryptoKeys/k1/cryptoKeyVersions/1'
         .format(_DEFAULT_PROJECT, _DEFAULT_LOCATION)
     ]
示例#21
0
    def SetUp(self):
        self.StartObjectPatch(dev, 'Skaffold')
        properties.VALUES.core.project.Set('myproject')
        self.addCleanup(properties.VALUES.core.project.Set, None)

        self.parser = util.ArgumentParser()
        code.Code.Args(self.parser)
        dev.Dev.Args(self.parser)

        self.find_executable_on_path = self.StartObjectPatch(
            file_utils, 'FindExecutableOnPath', return_value=True)
示例#22
0
    def SetUp(self):
        self.parser = util.ArgumentParser()
        create.Create.Args(self.parser)

        mock_fn = mock.patch.object(
            locations,
            'GetSupportedLocations',
            autospec=True,
            return_value=['us-west1', 'us-east1', 'europe-west1'])
        mock_fn.start()
        self.addCleanup(mock_fn.stop)
示例#23
0
 def testAddArgsForAddIamPolicyBindingAddCondition_NoneCondition(self):
     parser = util.ArgumentParser()
     iam_util.AddArgsForAddIamPolicyBinding(parser, add_condition=True)
     res = parser.parse_args(
         ['--role=roles/viewer', '--member=guest', '--condition=None'])
     self.assertEqual(res.role, 'roles/viewer')
     self.assertEqual(res.member, 'guest')
     self.assertTrue('None' in res.condition)
     self.assertFalse('expression' in res.condition)
     self.assertFalse('title' in res.condition)
     self.assertFalse('description' in res.condition)
示例#24
0
 def testValidateAndExtractConditionMutex_PrimitiveRole(self):
     parser = util.ArgumentParser()
     iam_util.AddArgsForAddIamPolicyBinding(parser, add_condition=True)
     res = parser.parse_args([
         '--role=roles/editor', '--member=user:[email protected]',
         '--condition=expression=expr,title=title,description=descr'
     ])
     with self.AssertRaisesExceptionRegexp(
             iam_util.IamPolicyBindingInvalidError,
             r'.*Binding with a condition and a primitive role is not allowed.*'
     ):
         iam_util.ValidateAndExtractConditionMutexRole(res)
示例#25
0
 def SetUp(self):
     self.parser = calliope_util.ArgumentParser()
     flags.AddParentFlagsToParser(self.parser)
     self.parser.add_argument('--location',
                              metavar='LOCATION',
                              help='Location')
     self.parser.add_argument('--recommender',
                              metavar='RECOMMENDER',
                              help='Recommender of recommendation')
     self.parser.add_argument('--insight-type',
                              metavar='Insight Type',
                              help='Insight Type of the insights')
示例#26
0
    def testWorkerAcceleratorType(self, index, accelerator, expected_count):
        parser = util.ArgumentParser()
        expected_type = self._getAcceleratorTypes()[index]
        flags.GetWorkerAccelerator().AddToParser(parser)
        args = parser.parse_args([
            '--worker-accelerator',
            'type={0},count={1}'.format(accelerator['type'],
                                        accelerator['count'])
        ])

        self.assertEqual(expected_type, args.worker_accelerator['type'])
        self.assertEqual(expected_count, args.worker_accelerator['count'])
示例#27
0
    def SetUp(self):
        self.command = _GetAndUpdateCommand()

        parser = calliope_util.ArgumentParser()
        arguments.AddConstraintArgToParser(parser)
        arguments.AddResourceFlagsToParser(parser)
        arguments.AddConditionFlagToParser(parser)
        self.args_without_condition = parser.parse_args(
            [self.CONSTRAINT_A, self.RESOURCE_FLAG, self.RESOURCE_ID])
        self.args_with_condition = parser.parse_args([
            self.CONSTRAINT_A, self.RESOURCE_FLAG, self.RESOURCE_ID,
            self.CONDITION_FLAG, self.CONDITION_EXPRESSION_A
        ])
示例#28
0
 def testAddArgsForRemoveIamPolicyBindingAddCondition(self):
     parser = util.ArgumentParser()
     iam_util.AddArgsForRemoveIamPolicyBinding(parser, add_condition=True)
     res = parser.parse_args([
         '--role=roles/viewer', '--member=guest',
         '--condition=expression=ip=whitelist_ip,title=title_value,'
         'description=description_value'
     ])
     self.assertEqual(res.role, 'roles/viewer')
     self.assertEqual(res.member, 'guest')
     self.assertEqual(res.condition.get('expression'), 'ip=whitelist_ip')
     self.assertEqual(res.condition.get('title'), 'title_value')
     self.assertEqual(res.condition.get('description'), 'description_value')
示例#29
0
    def SetUp(self):
        self.StartObjectPatch(skaffold, 'PrintUrlThreadContext')
        self.StartObjectPatch(skaffold, 'Skaffold')
        properties.VALUES.core.project.Set('myproject')
        self.addCleanup(properties.VALUES.core.project.Set, None)

        self.parser = util.ArgumentParser()
        code.Code.Args(self.parser)
        dev.Dev.Args(self.parser)

        self.find_executable_on_path = self.StartObjectPatch(
            file_utils, 'FindExecutableOnPath', return_value=True)
        self.mock_run = self.StartObjectPatch(run_subprocess, 'Run')
示例#30
0
    def testWorkerAcceleratorTypeErrors(self):
        parser = util.ArgumentParser()
        flags.GetWorkerAccelerator().AddToParser(parser)
        with self.AssertRaisesExceptionMatches(cli_test_base.MockArgumentError,
                                               _INVALID_ACCELERATOR_MESSAGE):
            parser.parse_args(
                ['--worker-accelerator', 'type=bad_type,count=2'])

        with self.AssertRaisesExceptionMatches(
                cli_test_base.MockArgumentError,
                'The count of the accelerator '
                'must be greater than 0.'):
            parser.parse_args(
                ['--worker-accelerator', 'type=nvidia-tesla-p4,count=0'])