def test_Uri(self):
     self.assertEqual(
         StringSerialization.SerializeItem(
             UriTypeInfo(), Uri.FromString("https://foo.bar.baz")),
         "https://foo.bar.baz")
     self.assertRaises(
         ValidationException, lambda: StringSerialization.SerializeItem(
             UriTypeInfo(), "this is not a valid uri"))
 def test_Filename(self):
     self.assertEqual(
         StringSerialization.SerializeItem(
             FilenameTypeInfo(ensure_exists=False),
             os.path.join("foo", "bar")), "foo/bar")
     self.assertRaises(
         ValidationException, lambda: StringSerialization.SerializeItem(
             FilenameTypeInfo(), os.path.join("foo", "bar")))
 def test_Time(self):
     self.assertEqual(
         StringSerialization.SerializeItem(
             TimeTypeInfo(), datetime.time(hour=15, minute=15, second=12)),
         "15:15:12")
     self.assertRaises(
         ValidationException, lambda: StringSerialization.SerializeItem(
             TimeTypeInfo(), "this is not a valid time"))
 def test_Date(self):
     self.assertEqual(
         StringSerialization.SerializeItem(
             DateTypeInfo(), datetime.date(year=2018, month=4, day=28)),
         "2018-04-28")
     self.assertRaises(
         ValidationException, lambda: StringSerialization.SerializeItem(
             DateTypeInfo(), "this is not a valid date"))
 def test_Guid(self):
     self.assertEqual(
         StringSerialization.SerializeItem(
             GuidTypeInfo(),
             uuid.UUID("363D3427-1871-40C5-83DF-3C9D5CE7B60D")),
         "363D3427-1871-40C5-83DF-3C9D5CE7B60D".lower())
     self.assertRaises(
         ValidationException, lambda: StringSerialization.SerializeItem(
             GuidTypeInfo(), "this is not a valid guid"))
    def test_Bool(self):
        self.assertEqual(
            StringSerialization.SerializeItem(BoolTypeInfo(), True), "True")
        self.assertEqual(
            StringSerialization.SerializeItem(BoolTypeInfo(), False), "False")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                BoolTypeInfo(), "this is not a bool"))
    def test_Int(self):
        self.assertEqual(StringSerialization.SerializeItem(IntTypeInfo(), 20),
                         "20")
        self.assertEqual(StringSerialization.SerializeItem(IntTypeInfo(), -20),
                         "-20")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                IntTypeInfo(), "this is not a valid int"))
        self.assertRaises(
            ValidationException,
            lambda: StringSerialization.SerializeItem(IntTypeInfo(min=0), -10))
        self.assertRaises(
            ValidationException,
            lambda: StringSerialization.SerializeItem(IntTypeInfo(max=10), 20))
    def test_Float(self):
        self.assertEqual(
            StringSerialization.SerializeItem(FloatTypeInfo(), -10.5), "-10.5")
        self.assertEqual(
            StringSerialization.SerializeItem(FloatTypeInfo(), 10), "10")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                FloatTypeInfo(), "this is not a valid float"))
        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                FloatTypeInfo(min=0), -10))
        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                FloatTypeInfo(max=10), 20))
    def test_String(self):
        self.assertEqual(
            StringSerialization.SerializeItem(StringTypeInfo(), "test"),
            "test")

        self.assertRaises(
            ValidationException,
            lambda: StringSerialization.SerializeItem(StringTypeInfo(), 10))
        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                StringTypeInfo(min_length=2), "1"))
        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                StringTypeInfo(max_length=2), "123"))
        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                StringTypeInfo(validation_expression="test"), "TEST"))
    def test_DateTime(self):
        self.assertEqual(
            StringSerialization.SerializeItem(
                DateTimeTypeInfo(),
                datetime.datetime(year=2018,
                                  month=4,
                                  day=28,
                                  hour=14,
                                  minute=46,
                                  second=12)), "2018-04-28 14:46:12")
        self.assertEqual(
            StringSerialization.SerializeItem(DateTimeTypeInfo(),
                                              datetime.datetime(year=2018,
                                                                month=4,
                                                                day=28,
                                                                hour=14,
                                                                minute=46,
                                                                second=12),
                                              sep='T'), "2018-04-28T14:46:12")
        self.assertEqual(
            StringSerialization.SerializeItem(
                DateTimeTypeInfo(),
                datetime.datetime(year=2018,
                                  month=4,
                                  day=28,
                                  hour=14,
                                  minute=46,
                                  second=12,
                                  microsecond=3939)),
            "2018-04-28 14:46:12.003939")
        self.assertEqual(
            StringSerialization.SerializeItem(
                DateTimeTypeInfo(),
                datetime.datetime(year=2018,
                                  month=4,
                                  day=28,
                                  hour=14,
                                  minute=46,
                                  second=12,
                                  microsecond=3939),
                microseconds=False), "2018-04-28 14:46:12")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                DateTimeTypeInfo(), "this is not a datetime"))
    def test_Enum(self):
        self.assertEqual(
            StringSerialization.SerializeItem(EnumTypeInfo([
                "one",
                "two",
            ]), "one"), "one")
        self.assertEqual(
            StringSerialization.SerializeItem(EnumTypeInfo([
                "one",
                "two",
            ]), "two"), "two")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                EnumTypeInfo([
                    "one",
                    "two",
                ]), "three"))
        def DateAndBranch(date, branch, operator):
            assert date

            if branch:
                # ----------------------------------------------------------------------
                def BranchGenerator():
                    yield branch

                # ----------------------------------------------------------------------
            else:
                # ----------------------------------------------------------------------
                def BranchGenerator():
                    for branch in [
                            cls.GetCurrentBranch(repo_root),
                            cls.DefaultBranch,
                    ]:
                        yield branch

                # ----------------------------------------------------------------------

            assert BranchGenerator

            if not operator:
                operator = '<'
            else:
                operator = '>'

            errors = OrderedDict()

            for branch in BranchGenerator():
                command_line = '''hg log --branch "{branch}" --rev "sort(date('{operator}{date}'), -date)" --limit 1 --template "{{rev}}"''' \
                                    .format( branch=branch,
                                             operator=operator,
                                             date=StringSerialization.SerializeItem(DateTimeTypeInfo(), date, microseconds=False),
                                           )

                result, output = cls.Execute(repo_root,
                                             command_line,
                                             strip=True)

                if result == 0 and output:
                    return output

                errors[command_line] = output

            raise Exception(
                "Change not found ({branch}, {date})\n{errors}".format(
                    branch=branch,
                    date=date,
                    errors='\n\n'.join([
                        "{}\n{}".format(k, v) for k, v in six.iteritems(errors)
                    ]),
                ))
    def test_Duration(self):
        self.assertEqual(
            StringSerialization.SerializeItem(DurationTypeInfo(),
                                              datetime.timedelta(hours=2)),
            "2:00:00")
        self.assertEqual(
            StringSerialization.SerializeItem(
                DurationTypeInfo(), datetime.timedelta(days=1, hours=2)),
            "1.02:00:00")
        self.assertEqual(
            StringSerialization.SerializeItem(DurationTypeInfo(),
                                              datetime.timedelta(days=1,
                                                                 hours=2),
                                              sep=':'), "1:02:00:00")
        self.assertEqual(
            StringSerialization.SerializeItem(
                DurationTypeInfo(),
                datetime.timedelta(days=1, hours=2, microseconds=3456)),
            "1.02:00:00.003456")

        self.assertRaises(
            ValidationException, lambda: StringSerialization.SerializeItem(
                DurationTypeInfo(), "this is not a valid duration"))
Esempio n. 14
0
    def GetChangesSinceLastMerge(cls,
                                 repo_root,
                                 dest_branch,
                                 source_merge_arg=None):
        # Git is really screwed up. After a 30 minute search, I couldn't find a way to
        # specify a branch and beginning revision in a single command. Therefore, I am
        # doing it manually.

        source_branch = None
        additional_filters = []
        post_decorator_func = None

        # ----------------------------------------------------------------------
        def GetDateOperator(arg):
            if arg is None or arg:
                return "since"

            return "until"

        # ----------------------------------------------------------------------

        if source_merge_arg is None or isinstance(source_merge_arg,
                                                  EmptyUpdateMergeArg):
            source_branch = cls.GetCurrentBranch(repo_root)

        elif isinstance(source_merge_arg, ChangeUpdateMergeArg):
            source_branch = cls._GetBranchAssociatedWithChange(
                source_merge_arg.Change)

            # ----------------------------------------------------------------------
            def AfterChangeDecorator(changes):
                starting_index = None

                for index, change in enumerate(changes):
                    if change == source_merge_arg.Change:
                        starting_index = index
                        break

                if starting_index is None:
                    return []

                return changes[starting_index:]

            # ----------------------------------------------------------------------

            post_decorator_func = AfterChangeDecorator

        elif isinstance(source_merge_arg, DateUpdateMergeArg):
            source_branch = cls.GetCurrentBranch(repo_root)
            additional_filters.append('--{}="{}"'.format(
                GetDateOperator(source_merge_arg.GreaterThan),
                StringSerialization.SerializeItem(DateTimeTypeInfo(),
                                                  source_merge_arg.Date),
            ))

        elif isinstance(source_merge_arg, BranchUpdateMergeArg):
            source_branch = source_merge_arg.Branch

        elif isinstance(source_merge_arg, BranchAndDateUpdateMergeArg):
            source_branch = source_merge_arg.Branch
            additional_filters.append('--{}="{}"'.format(
                GetDateOperator(source_merge_arg.GreaterThan),
                StringSerialization.SerializeItem(DateTimeTypeInfo(),
                                                  source_merge_arg.Date),
            ))

        else:
            assert False, type(source_merge_arg)

        command_line = 'git --no-pager log "{source_branch}" --not "{dest_branch}" --format="%H" --no-merges{additional_filters}' \
                            .format( source_branch=source_branch,
                                     dest_branch=dest_branch,
                                     additional_filters='' if not additional_filters else " {}".format(' '.join(additional_filters)),
                                   )

        result, output = cls.Execute(repo_root, command_line)
        assert result == 0, (result, output)

        changes = [line.strip() for line in output.split('\n') if line.strip()]

        if post_decorator_func:
            changes = post_decorator_func(changes)

        return changes
Esempio n. 15
0
        def ApplyImpl(parameter, arg):
            if isinstance(parameter.TypeInfo, DictTypeInfo):
                # Add the dictionary values; we will validate later.
                match = self._dict_regex.match(arg)
                if not match:
                    return "'{}' is not a valid dictionary entry".format(arg)

                tag = match.group("tag")
                tag = tag.replace(
                    "\\{}".format(self.CommandLineDictTagValueSeparator),
                    self.CommandLineDictTagValueSeparator)

                value = match.group("value")

                argument_values.setdefault(parameter.Name, OrderedDict())

                if tag not in argument_values[parameter.Name]:
                    if parameter.AllowDuplicates:
                        argument_values[parameter.Name][tag] = [
                            value,
                        ]
                    else:
                        argument_values[parameter.Name][tag] = value
                else:
                    if not parameter.AllowDuplicates:
                        return "A value for '{}'s tag '{}' has already been provided ({})".format(
                            parameter.Name,
                            tag,
                            argument_values[parameter.Name][tag],
                        )

                    argument_values[parameter.Name][tag].append(value)

                return None

            if parameter.IsSwitch:
                # Preserve the value as a string so it can be deserialized below
                arg = StringSerialization.SerializeItem(
                    parameter.TypeInfo, not parameter.DefaultValue)

            try:
                if isinstance(parameter.TypeInfo,
                              tuple(ALL_FUNDAMENTAL_TYPES)):
                    value = StringSerialization.DeserializeItem(
                        parameter.TypeInfo, arg)
                elif isinstance(parameter.TypeInfo, AnyOfTypeInfo):
                    found = False

                    for eti in parameter.TypeInfo.ElementTypeInfos:
                        try:
                            value = StringSerialization.DeserializeItem(
                                eti, arg)
                            found = True
                            break
                        except ValidationException:
                            pass

                    if not found:
                        value = arg

                else:
                    value = arg

                if parameter.PostprocessFunc:
                    value = parameter.PostprocessFunc(value)

            except ValidationException as ex:
                return str(ex)

            if parameter.DisplayArity in [
                    '?',
                    '1',
            ]:
                if parameter.Name in argument_values:
                    return "A value for '{}' has already been provided ({})".format(
                        parameter.Name,
                        argument_values[parameter.Name],
                    )

                argument_values[parameter.Name] = value

            elif parameter.DisplayArity in [
                    '*',
                    '+',
            ]:
                argument_values.setdefault(parameter.Name, []).append(value)

            else:
                assert False

            return None
    def GetChangesSinceLastMerge(cls,
                                 repo_root,
                                 dest_branch,
                                 source_merge_arg=None):
        source_branch = None
        additional_filters = []

        # ----------------------------------------------------------------------
        def GetDateOperator(arg):
            if arg is None or arg:
                return '>'

            return '<'

        # ----------------------------------------------------------------------

        if isinstance(source_merge_arg, EmptyUpdateMergeArg):
            source_branch = cls.GetCurrentBranch(repo_root)

        elif isinstance(source_merge_arg, ChangeUpdateMergeArg):
            source_branch = cls._GetBranchAssociatedWithChange(
                repo_root, source_merge_arg.Change)
            additional_filters.append("{}::".format(source_merge_arg.Change))

        elif isinstance(source_merge_arg, DateUpdateMergeArg):
            source_branch = cls.GetCurrentBranch(repo_root)
            additional_filters.append("date('{}{}')".format(
                GetDateOperator(source_merge_arg.GreaterThan),
                StringSerialization.SerializeItem(DateTimeTypeInfo(),
                                                  source_merge_arg.Date,
                                                  microseconds=False),
            ))

        elif isinstance(source_merge_arg, BranchAndDateUpdateMergeArg):
            source_branch = source_merge_arg.Branch
            additional_filters.append("date('{}{}')".format(
                GetDateOperator(source_merge_arg.GreaterThan),
                StringSerialization.SerializeItem(DateTimeTypeInfo(),
                                                  source_merge_arg.Date,
                                                  microseconds=False),
            ))

        elif isinstance(source_merge_arg, BranchUpdateMergeArg):
            source_branch = source_merge_arg.Branch

        else:
            assert False, type(source_merge_arg)

        filter = "::{} and not ::{}".format(source_branch, dest_branch)
        if additional_filters:
            filter += " and {}".format(" and ".join(additional_filters))

        command_line = r'hg log --branch "{source_branch}" --rev "{filter}" --template "{{rev}}\n"' \
                            .format( source_branch=source_branch,
                                     filter=filter,
                                   )

        result, output = cls.Execute(repo_root, command_line)
        assert result == 0, (result, output)

        return [line.strip() for line in output.split('\n') if line.strip()]