Python typing.List() Examples

The following are 30 code examples for showing how to use typing.List(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module typing , or try the search function .

Example 1
Project: clikit   Author: sdispater   File: event_dispatcher.py    License: MIT License 8 votes vote down vote up
def get_listeners(
        self, event_name=None
    ):  # type: (str) -> Union[List[Callable], Dict[str, Callable]]
        if event_name is not None:
            if event_name not in self._listeners:
                return []

            if event_name not in self._sorted:
                self._sort_listeners(event_name)

            return self._sorted[event_name]

        for event_name, event_listeners in self._listeners.items():
            if event_name not in self._sorted:
                self._sort_listeners(event_name)

        return self._sorted 
Example 2
Project: clikit   Author: sdispater   File: args_format.py    License: MIT License 7 votes vote down vote up
def _create_builder_for_elements(
        self, elements, base_format=None
    ):  # type: (List[Any], Optional[ArgsFormat]) -> ArgsFormatBuilder
        from .args_format_builder import ArgsFormatBuilder

        builder = ArgsFormatBuilder(base_format)

        for element in elements:
            if isinstance(element, CommandName):
                builder.add_command_name(element)
            elif isinstance(element, CommandOption):
                builder.add_command_option(element)
            elif isinstance(element, Option):
                builder.add_option(element)
            elif isinstance(element, Argument):
                builder.add_argument(element)

        return builder 
Example 3
Project: mutatest   Author: EvanKepner   File: run.py    License: MIT License 6 votes vote down vote up
def clean_trial(src_loc: Path, test_cmds: List[str]) -> timedelta:
    """Remove all existing cache files and run the test suite.

    Args:
        src_loc: the directory of the package for cache removal, may be a file
        test_cmds: test running commands for subprocess.run()

    Returns:
        None

    Raises:
        BaselineTestException: if the clean trial does not pass from the test run.
    """
    cache.remove_existing_cache_files(src_loc)

    LOGGER.info("Running clean trial")

    # clean trial will show output all the time for diagnostic purposes
    start = datetime.now()
    clean_run = subprocess.run(test_cmds, capture_output=False)
    end = datetime.now()

    if clean_run.returncode != 0:
        raise BaselineTestException(
            f"Clean trial does not pass, mutant tests will be meaningless.\n"
            f"Output: {str(clean_run.stdout)}"
        )

    return end - start


####################################################################################################
# MUTATION SAMPLE GENERATION
#################################################################################################### 
Example 4
Project: mutatest   Author: EvanKepner   File: cli.py    License: MIT License 6 votes vote down vote up
def selected_categories(whitelist: List[str], blacklist: List[str]) -> List[str]:
    """Create the selected categories from the whitelist/blacklist set to use in filtering.

    Args:
        whitelist: list of categories
        blacklist: list of categories

    Returns:
        Selection set of mutation categories
    """
    all_mutations = {m.category for m in transformers.get_compatible_operation_sets()}
    w_set = set(whitelist)
    b_set = set(blacklist)

    if w_set:
        return list(w_set - b_set)

    return list(all_mutations - b_set) 
Example 5
Project: mutatest   Author: EvanKepner   File: conftest.py    License: MIT License 6 votes vote down vote up
def write_cov_file(line_data: Dict[str, List[int]], fname: str) -> None:
    """Write a coverage file supporting both Coverage v4 and v5.

    Args:
        line_data: Dictionary of line data for the coverage file.
        fname: string filename for output location (absolute path)

    Returns:
        None
    """
    if coverage.version_info[0] == 4:
        covdata = coverage.CoverageData()
        covdata.add_lines(line_data)
        covdata.write_file(fname)

    else:
        # assume coverage v 5
        covdata = coverage.CoverageData(basename=fname)
        covdata.add_lines(line_data)
        covdata.write()


####################################################################################################
# CLI: MOCK ARGS
#################################################################################################### 
Example 6
Project: clikit   Author: sdispater   File: command_option.py    License: MIT License 6 votes vote down vote up
def __init__(
        self, long_name, short_name=None, aliases=None, flags=0, description=None
    ):  # type: (str, Optional[str], Optional[List[str]], int, Optional[str]) -> None
        super(CommandOption, self).__init__(long_name, short_name, flags, description)

        if aliases is None:
            aliases = []

        self._long_aliases = []
        self._short_aliases = []

        for alias in aliases:
            alias = self._remove_dash_prefix(alias)

            if len(alias) == 1:
                self._validate_short_alias(alias)
                self._short_aliases.append(alias)
            else:
                self._validate_long_alias(alias)
                self._long_aliases.append(alias) 
Example 7
Project: clikit   Author: sdispater   File: cell_wrapper.py    License: MIT License 6 votes vote down vote up
def _wrap_column(
        self, col, column_length, formatter
    ):  # type: (int, List[int], Formatter) -> None
        for i, row in enumerate(self._wrapped_rows):
            cell = row[col]
            cell_length = self._cell_lengths[i][col]

            if cell_length > column_length:
                self._word_wraps = True

                if not self._word_cuts:
                    min_length_without_cut = get_max_word_length(cell, formatter)

                    if min_length_without_cut > column_length:
                        self._word_cuts = True

                # TODO: use format aware wrapper
                wrapped_cell = "\n".join(textwrap.wrap(cell, column_length))

                self._wrapped_rows[i][col] = wrapped_cell

                # Refresh cell length
                self._cell_lengths[i][col] = get_max_line_length(
                    wrapped_cell, formatter
                ) 
Example 8
Project: clikit   Author: sdispater   File: default_args_parser.py    License: MIT License 6 votes vote down vote up
def _parse_long_option(
        self, token, tokens, fmt, lenient
    ):  # type: (str, List[str], ArgsFormat, bool) -> None
        name = token[2:]
        pos = name.find("=")
        if pos != -1:
            self._add_long_option(name[:pos], name[pos + 1 :], tokens, fmt, lenient)
        else:
            if fmt.has_option(name) and fmt.get_option(name).accepts_value():
                try:
                    value = tokens.pop(0)
                except IndexError:
                    value = None

                if value and value.startswith("-"):
                    tokens.insert(0, value)
                    value = None

                self._add_long_option(name, value, tokens, fmt, lenient)
            else:
                self._add_long_option(name, None, tokens, fmt, lenient) 
Example 9
Project: clikit   Author: sdispater   File: default_args_parser.py    License: MIT License 6 votes vote down vote up
def _parse_short_option(
        self, token, tokens, fmt, lenient
    ):  # type: (str, List[str], ArgsFormat, bool) -> None
        name = token[1:]
        if len(name) > 1:
            if fmt.has_option(name[0]) and fmt.get_option(name[0]).accepts_value():
                # an option with a value (with no space)
                self._add_short_option(name[0], name[1:], tokens, fmt, lenient)
            else:
                self._parse_short_option_set(name, tokens, fmt, lenient)
        else:
            if fmt.has_option(name[0]) and fmt.get_option(name[0]).accepts_value():
                try:
                    value = tokens.pop(0)
                except IndexError:
                    value = None

                if value and value.startswith("-"):
                    tokens.insert(0, value)
                    value = None

                self._add_short_option(name, value, tokens, fmt, lenient)
            else:
                self._add_short_option(name, None, tokens, fmt, lenient) 
Example 10
Project: clikit   Author: sdispater   File: default_args_parser.py    License: MIT License 6 votes vote down vote up
def _parse_short_option_set(
        self, name, tokens, fmt, lenient
    ):  # type: (str, List[str], ArgsFormat, bool) -> None
        l = len(name)
        for i in range(0, l):
            if not fmt.has_option(name[i]):
                raise NoSuchOptionException(name[i])

            option = fmt.get_option(name[i])
            if option.accepts_value():
                self._add_long_option(
                    option.long_name,
                    None if l - 1 == i else name[i + 1 :],
                    tokens,
                    fmt,
                    lenient,
                )

                break
            else:
                self._add_long_option(option.long_name, None, tokens, fmt, lenient) 
Example 11
Project: clikit   Author: sdispater   File: default_resolver.py    License: MIT License 6 votes vote down vote up
def process_arguments(
        self, args, named_commands, arguments_to_test, options_to_test
    ):  # type: (RawArgs, CommandCollection, List[str], List[str]) -> Optional[ResolveResult]
        current_command = None

        # Parse the arguments for command names until we fail to find a
        # matching command
        for name in arguments_to_test:
            if name not in named_commands:
                break

            next_command = named_commands.get(name)

            current_command = next_command
            named_commands = current_command.named_sub_commands

        if not current_command:
            return

        return self.process_options(args, current_command, options_to_test) 
Example 12
Project: clikit   Author: sdispater   File: default_resolver.py    License: MIT License 6 votes vote down vote up
def get_options_to_test(self, tokens):  # type: (Iterator[str]) -> List[str]
        options_to_test = []
        token = next(tokens, None)

        while token:
            # "--" stops option parsing
            if token == "--":
                break

            if token[:1] and token[0] == "-":
                if token[:2] == "--" and len(token) > 2:
                    options_to_test.append(token[2:])
                elif len(token) == 2:
                    options_to_test.append(token[1:])

            token = next(tokens, None)

        return options_to_test 
Example 13
Project: mutatest   Author: EvanKepner   File: report.py    License: MIT License 5 votes vote down vote up
def get_reported_results(trial_results: List[MutantTrialResult], status: str) -> ReportedMutants:
    """Utility function to create filtered lists of mutants based on status.

    Args:
        trial_results: list of mutant trial results
        status: the status to filter by

    Returns:
        The reported mutants as a ``ReportedMutants`` container.
    """
    mutants = [t.mutant for t in trial_results if t.status == status]
    return ReportedMutants(status, mutants) 
Example 14
Project: mutatest   Author: EvanKepner   File: report.py    License: MIT License 5 votes vote down vote up
def get_status_summary(trial_results: List[MutantTrialResult]) -> Dict[str, Union[str, int]]:
    """Create a status summary dictionary for later formatting.

    Args:
        trial_results: list of mutant trials

    Returns:
        Dictionary with keys for formatting in the report
    """
    status: Dict[str, Union[str, int]] = dict(Counter([t.status for t in trial_results]))
    status["TOTAL RUNS"] = len(trial_results)
    status["RUN DATETIME"] = str(datetime.now())

    return status 
Example 15
Project: mutatest   Author: EvanKepner   File: run.py    License: MIT License 5 votes vote down vote up
def get_sample(ggrp: GenomeGroup, ignore_coverage: bool) -> List[GenomeGroupTarget]:
    """Get the sample space for the mutation trials.

    This will attempt to use covered-targets as the default unless ``ignore_coverage`` is set
    to True. If the set .coverage file is not found then the total targets are returned instead.

    Args:
        ggrp: the Genome Group to generate the sample space of targets
        ignore_coverage: flag to ignore coverage if present

    Returns:
        Sorted list of Path-LocIndex pairs as complete sample space from the ``GenomeGroup``.
    """
    if ignore_coverage:
        LOGGER.info("Ignoring coverage file for sample space creation.")

    try:
        sample = ggrp.targets if ignore_coverage else ggrp.covered_targets

    except FileNotFoundError:
        LOGGER.info("Coverage file does not exist, proceeding to sample from all targets.")
        sample = ggrp.targets

    # sorted list used for repeat trials using random seed instead of set
    sort_by_keys = attrgetter(
        "source_path",
        "loc_idx.lineno",
        "loc_idx.col_offset",
        "loc_idx.end_lineno",
        "loc_idx.end_col_offset",
    )
    return sorted(sample, key=sort_by_keys) 
Example 16
Project: mutatest   Author: EvanKepner   File: run.py    License: MIT License 5 votes vote down vote up
def create_mutation_run_trial(
    genome: Genome, target_idx: LocIndex, mutation_op: Any, test_cmds: List[str], max_runtime: float
) -> MutantTrialResult:
    """Run a single mutation trial by creating a new mutated cache file, running the
    test commands, and then removing the mutated cache file.

    Args:
        genome: the genome to mutate
        target_idx: the mutation location
        mutation_op: the mutation operation
        test_cmds: the test commands to execute with the mutated code
        max_runtime: timeout for the trial

    Returns:
        The mutation trial result
    """
    LOGGER.debug("Running trial for %s", mutation_op)

    mutant = genome.mutate(target_idx, mutation_op, write_cache=True)

    try:
        mutant_trial = subprocess.run(
            test_cmds,
            capture_output=capture_output(LOGGER.getEffectiveLevel()),
            timeout=max_runtime,
        )
        return_code = mutant_trial.returncode

    except subprocess.TimeoutExpired:
        return_code = 3

    cache.remove_existing_cache_files(mutant.src_file)

    return MutantTrialResult(
        mutant=MutantReport(
            src_file=mutant.src_file, src_idx=mutant.src_idx, mutation=mutant.mutation
        ),
        return_code=return_code,
    ) 
Example 17
Project: mutatest   Author: EvanKepner   File: transformers.py    License: MIT License 5 votes vote down vote up
def get_mutations_for_target(target: LocIndex) -> Set[Any]:
    """Given a target, find all the mutations that could apply from the AST definitions.

    Args:
        target: the location index target

    Returns:
        Set of types that can mutated into the target location.
    """
    search_space: List[Set[Any]] = [m.operations for m in get_compatible_operation_sets()]
    mutation_ops: Set[Any] = set()

    for potential_ops in search_space:
        if target.op_type in potential_ops:
            LOGGER.debug("Potential mutatest operations found for target: %s", target.op_type)
            mutation_ops = potential_ops.copy()
            mutation_ops.remove(target.op_type)

            # Special case for If_Statement since that is a default to transform to True or False
            # but not a validation mutation target by itself
            if "If_Statement" in mutation_ops:
                mutation_ops.remove("If_Statement")

            break

    return mutation_ops 
Example 18
Project: mutatest   Author: EvanKepner   File: cli.py    License: MIT License 5 votes vote down vote up
def read_ini_config(
    config_path: Path, sections: Optional[List[str]] = None
) -> configparser.SectionProxy:
    """Read a config_path using ConfigParser

    Args:
        config_path: path to the INI config file
        sections: sections of config file to return, default to ['mutatest'] if None

    Returns:
        config section proxy

    Raises:
        KeyError if ``section`` not in ``config_path``.
    """

    sections = sections or ["mutatest"]
    config = configparser.ConfigParser()
    # ensures [  mutatest  ] is valid like [mutatest] in a section key
    config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")  # type: ignore

    config.read(config_path)

    # Attempt sections in the list, if none are matched raise a KeyError
    for section in sections:
        try:
            return config[section]
        except KeyError:
            continue

    raise KeyError 
Example 19
Project: mutatest   Author: EvanKepner   File: cli.py    License: MIT License 5 votes vote down vote up
def exception_processing(n_survivors: int, trial_results: List[MutantTrialResult]) -> None:
    """Raise a custom mutation exception if ``n_survivors`` count is met.

    Args:
        n_survivors: tolerance number for survivors
        trial_results: results from the trials

    Returns:
        None

    Raises:
        SurvivingMutantException: if the number of survivors is exceeded.
    """
    survived = report.get_reported_results(trial_results, "SURVIVED")
    if len(survived.mutants) >= n_survivors:
        message = run.colorize_output(
            f"Survivor tolerance breached: {len(survived.mutants)} / {n_survivors}", "red"
        )
        raise SurvivingMutantException(message)

    LOGGER.info(
        "%s",
        run.colorize_output(
            f"Survivor tolerance OK: {len(survived.mutants)} / {n_survivors}", "green"
        ),
    )


####################################################################################################
# MAIN COMMAND LINE ROUTINE
#################################################################################################### 
Example 20
Project: clikit   Author: sdispater   File: style_set.py    License: MIT License 5 votes vote down vote up
def __init__(self, styles=None):  # type: (Optional[List[Style]]) -> None
        if styles is None:
            styles = []

        self._styles = {}

        for style in styles:
            self.add(style) 
Example 21
Project: clikit   Author: sdispater   File: style_set.py    License: MIT License 5 votes vote down vote up
def replace(self, styles):  # type: (Optional[List[Style]]) -> None
        self._styles = {}

        for style in styles:
            self.add(style) 
Example 22
Project: clikit   Author: sdispater   File: raw_args.py    License: MIT License 5 votes vote down vote up
def tokens(self):  # type: () -> List[str]
        raise NotImplementedError() 
Example 23
Project: clikit   Author: sdispater   File: raw_args.py    License: MIT License 5 votes vote down vote up
def option_tokens(self):  # type: () -> List[str]
        raise NotImplementedError()
        return list(itertools.takewhile(lambda arg: arg != "--", self.tokens)) 
Example 24
Project: clikit   Author: sdispater   File: args_format_builder.py    License: MIT License 5 votes vote down vote up
def get_command_names(self, include_base=True):  # type: (bool) -> List[CommandName]
        command_names = self._command_names

        if include_base and self._base_format:
            command_names = self._base_format.get_command_names() + command_names

        return command_names 
Example 25
Project: clikit   Author: sdispater   File: command_name.py    License: MIT License 5 votes vote down vote up
def aliases(self):  # type: () -> List[str]
        return self._aliases 
Example 26
Project: clikit   Author: sdispater   File: command_option.py    License: MIT License 5 votes vote down vote up
def long_aliases(self):  # type: () -> List[str]
        return self._long_aliases 
Example 27
Project: clikit   Author: sdispater   File: command_option.py    License: MIT License 5 votes vote down vote up
def short_aliases(self):  # type: () -> List[str]
        return self._short_aliases 
Example 28
Project: clikit   Author: sdispater   File: args_format.py    License: MIT License 5 votes vote down vote up
def get_command_options(
        self, include_base=True
    ):  # type: (bool) -> List[CommandOption]
        command_options = list(self._command_options.values())

        if include_base and self._base_format:
            command_options += self._base_format.get_command_options()

        return command_options 
Example 29
Project: clikit   Author: sdispater   File: event_dispatcher.py    License: MIT License 5 votes vote down vote up
def _do_dispatch(
        self, listeners, event_name, event
    ):  # type: (List[Callable], str, Event) -> None
        for listener in listeners:
            if event.is_propagation_stopped():
                break

            listener(event, event_name, self) 
Example 30
Project: clikit   Author: sdispater   File: application_config.py    License: MIT License 5 votes vote down vote up
def __init__(
        self, name=None, version=None
    ):  # type: (Optional[str], Optional[str]) -> None
        self._name = name
        self._version = version
        self._display_name = None
        self._help = None
        self._command_configs = []  # type: List[CommandConfig]
        self._catch_exceptions = True
        self._terminate_after_run = True
        self._command_resolver = None
        self._io_factory = None
        self._debug = False
        self._style_set = None
        self._dispatcher = None
        self._pre_resolve_hooks = []  # type: List[Callable]

        if PY36:
            from crashtest.solution_providers.solution_provider_repository import (
                SolutionProviderRepository,
            )

            self._solution_provider_repository = SolutionProviderRepository()
        else:
            self._solution_provider_repository = None

        super(ApplicationConfig, self).__init__()