### Define source location for example files Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Sets the source location for the example Python files ('a.py' and 'b.py') and their corresponding test file ('test_ab.py'). This Path object is used to access these files throughout the tutorial. ```python # This folder and included .py files are in docs/api_tutoral/ src_loc = Path("example") ``` -------------------------------- ### Install Mutatest using pip Source: https://mutatest.readthedocs.io/en/latest_badge=latest Installs the Mutatest mutation testing tool from the Python Package Index (PyPI). This is the standard method for installing Python packages. ```bash $ pip install mutatest ``` -------------------------------- ### Mutatest SurvivingMutantException Example Source: https://mutatest.readthedocs.io/en/latest/commandline Illustrates the format of the `SurvivingMutantException` raised by Mutatest when survivor tolerance is breached during mutation trials. ```text ... prior output from trial... mutatest.cli.SurvivingMutantException: Survivor tolerance breached: 8 / 2 ``` -------------------------------- ### Install Mutatest from source Source: https://mutatest.readthedocs.io/en/latest_badge=latest Installs Mutatest directly from its source code repository. This method is useful for developers who want to work with the latest code or contribute to the project. ```bash cd mutatest $ pip install . ``` -------------------------------- ### Run Mutatest for API Tutorial Example Source: https://mutatest.readthedocs.io/en/latest This command initiates a mutation trial using mutatest. It specifies the source directory ('example/'), the test command ('pytest'), and a random seed ('314') for reproducibility. The output shows the mutation process, including clean trials, identified mutation targets, and the final diagnostic summary. ```bash $ mutatest -s example/ -t "pytest" -r 314 Running clean trial 2 mutation targets found in example/a.py AST. 1 mutation targets found in example/b.py AST. Setting random.seed to: 314 Total sample space size: 2 10 exceeds sample space, using full sample: 2. Starting individual mutation trials! Current target location: a.py, LocIndex(ast_class='BinOp', lineno=6, col_offset=11, op_type=) Detected mutation at example/a.py: (6, 11) Detected mutation at example/a.py: (6, 11) Surviving mutation at example/a.py: (6, 11) Break on survival: stopping further mutations at location. Current target location: b.py, LocIndex(ast_class='CompareIs', lineno=6, col_offset=11, op_type=) Detected mutation at example/b.py: (6, 11) Running clean trial Mutatest diagnostic summary =========================== - Source location: /home/user/Github/mutatest/docs/api_tutorial/example - Test commands: ['pytest'] - Mode: s - Excluded files: [] - N locations input: 10 - Random seed: 314 Random sample details --------------------- - Total locations mutated: 2 - Total locations identified: 2 - Location sample coverage: 100.00 % Running time details -------------------- - Clean trial 1 run time: 0:00:00.348999 - Clean trial 2 run time: 0:00:00.350213 - Mutation trials total run time: 0:00:01.389095 Trial Summary Report: Overall mutation trial summary ============================== - DETECTED: 3 - SURVIVED: 1 - TOTAL RUNS: 4 - RUN DATETIME: 2019-10-17 16:57:08.645355 Detected mutations: DETECTED -------- - example/a.py: (l: 6, c: 11) - mutation from to - example/a.py: (l: 6, c: 11) - mutation from to - example/b.py: (l: 6, c: 11) - mutation from to Surviving mutations: SURVIVED -------- - example/a.py: (l: 6, c: 11) - mutation from to ``` -------------------------------- ### Install Mutatest using conda Source: https://mutatest.readthedocs.io/en/latest_badge=latest Installs the Mutatest mutation testing tool from the conda-forge channel. This is an alternative installation method for users who prefer using the Conda package manager. ```bash $ conda install -c conda-forge mutatest ``` -------------------------------- ### Set Filter Codes on GenomeGroup Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Shows how to apply filter codes to all Genomes within a GenomeGroup. The example filters targets to only those with the ('cs',) filter code, simplifying the analysis of specific mutation types. ```python # Setting filter codes on all Genomes # in the group ggrp.set_filter(("cs",)) ggrp.targets for k, v in ggrp.items(): print(k, v.filter_codes) ``` -------------------------------- ### List files in the source directory Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Prints a list of all files within the specified source directory ('example/'). This helps in visualizing the files involved in the tutorial. ```python print(*[i for i in src_loc.iterdir() if i.is_file()], sep="\n") ``` -------------------------------- ### Run Mutation Trial and Check Status Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Demonstrates how to run a mutation trial with a specific genome, mutation target, AST class, and test runner, then access its status. It requires the 'mutatest' library and potentially a testing framework like 'pytest'. ```python mutant_trial_result = run.create_mutation_run_trial( genome, mutation_target, ast.Div, ["pytest"], max_runtime=5 ) mutant_trial_result.status ``` -------------------------------- ### Import necessary modules for mutatest API tutorial Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Imports essential modules for the mutatest API tutorial, including AST, Path, run, transformers, Genome, GenomeGroup, MutationException, CoverageFilter, and CategoryCodeFilter. These are used throughout the tutorial for various operations. ```python import ast from pathlib import Path from mutatest import run from mutatest import transformers from mutatest.api import Genome, GenomeGroup, MutationException from mutatest.filters import CoverageFilter, CategoryCodeFilter ``` -------------------------------- ### BinOp Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Illustrates binary operation mutations for arithmetic operators like +, -, /, *, etc. The example shows `x = a + b` being mutated to `x = a / b` or `x = a - b`. ```Python # source code x = a + b # mutations x = a / b # ast.Div x = a - b # ast.Sub ``` -------------------------------- ### Create and Inspect GenomeGroup Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Shows how to initialize a GenomeGroup from a source location and iterate through its key-value pairs, where keys are file paths and values are Genome objects. This is useful for managing multiple genomes and accessing their shared properties. ```python ggrp = GenomeGroup(src_loc) # key-value pairs in the GenomeGroup are # the path to the source file # and the Genome object for that file for k,v in ggrp.items(): print(k, v) ``` -------------------------------- ### BoolOp Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Illustrates mutations for boolean operations `and` and `or`. The condition `if x and y:` can be mutated to `if x or y:`. ```Python # source code if x and y: # mutation if x or y: ``` -------------------------------- ### BinOp Bitwise Shift Mutations - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Demonstrates mutations for bitwise shift operations `<<` and `>>`. The example `x >> y` can be mutated to `x << y`. ```Python # source code x >> y # mutation x << y ``` -------------------------------- ### Initialize Genome with source file location Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Initializes a `mutatest.api.Genome` object with the path to the source file 'example/a.py'. By default, the `coverage_file` property is set to '.coverage'. The Genome represents a source code file for mutation testing. ```python # Initialize with the source file location # By default, the ".coverage" file is set # for the coverage_file property genome = Genome(src_loc / "a.py") ``` -------------------------------- ### Perform a clean trial of test commands Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Executes a clean trial using `mutatest.run.clean_trial` with the specified source location and pytest commands. This generates a `.coverage` file, which is useful for resetting `__pycache__` and for subsequent mutation trials. ```python # The return value of clean_trial is the time to run # this is used in reporting from the CLI run.clean_trial( src_loc, test_cmds=["pytest", "--cov=example"] ) ``` -------------------------------- ### Get Mutations for Target Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/transformers Given a target location index, this function identifies all possible mutations that could be applied based on the AST definitions. ```APIDOC ## GET /websites/mutatest_readthedocs_io/transformer_functions/mutations_for_target ### Description Given a target, find all the mutations that could apply from the AST definitions. ### Method GET ### Endpoint /websites/mutatest_readthedocs_io/transformer_functions/mutations_for_target ### Parameters #### Path Parameters None #### Query Parameters - **target** (LocIndex) - Required - The target location index for which to find mutations. ### Request Example None ### Response #### Success Response (200) - **mutations** (Set[Any]) - A set of all applicable mutations for the given target. #### Response Example ```json { "mutations": [ "MutationType1", "MutationType2", "..." ] } ``` ``` -------------------------------- ### Add Folder to GenomeGroup with Tests Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Demonstrates adding all files from a folder to a GenomeGroup, with the option to include test files (`ignore_test_files=False`). This is useful for creating a comprehensive group of genomes for mutation analysis. ```python # the add_folder options provides # more flexibility e.g., to include # the test_ files. ggrp_with_tests = GenomeGroup() ggrp_with_tests.add_folder( src_loc, ignore_test_files=False ) for k, v in ggrp_with_tests.items(): print(k, v) ``` -------------------------------- ### Compare Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Shows mutations for comparison operators like `==`, `>=`, `<=`, `>`, `<`, and `!=`. The code `x >= y` can be mutated to `x < y`, `x > y`, or `x != y`. ```Python # source code x >= y # mutations x < y # ast.Lt x > y # ast.Gt x != y # ast.NotEq ``` -------------------------------- ### Get Compatible Operation Sets Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/transformers Retrieves a list of compatible AST mutations supported by mutatest, categorized for use in mutation testing and CLI help. ```APIDOC ## GET /websites/mutatest_readthedocs_io/transformer_functions/compatible_operation_sets ### Description Utility function to return a list of compatible AST mutations with names. All of the mutation transformation sets that are supported by mutatest are defined here. This is used to create the search space in finding mutations for a target, and also to list the support operations in the CLI help function. ### Method GET ### Endpoint /websites/mutatest_readthedocs_io/transformer_functions/compatible_operation_sets ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **operations** (List[MutationOpSet]) - A list of MutationOpSet objects, each detailing a mutation category, its description, supported operations, and category identifier. ```json { "operations": [ { "name": "AugAssign", "desc": "Augmented assignment e.g. += -= /= *=", "operations": [ "AugAssign_Add", "AugAssign_Sub", "AugAssign_Mult", "AugAssign_Div" ], "category": "CATEGORIES_AugAssign" }, { "name": "BinOp", "desc": "Binary operations e.g. + - * / %", "operations": [ "ast.Add", "ast.Sub", "ast.Div", "ast.Mult", "ast.Pow", "ast.Mod", "ast.FloorDiv" ], "category": "CATEGORIES_BinOp" }, { "name": "BinOp Bit Comparison", "desc": "Bitwise comparison operations e.g. x & y, x | y, x ^ y", "operations": [ "ast.BitAnd", "ast.BitOr", "ast.BitXor" ], "category": "CATEGORIES_BinOpBC" }, { "name": "BinOp Bit Shifts", "desc": "Bitwise shift operations e.g. << >>", "operations": [ "ast.LShift", "ast.RShift" ], "category": "CATEGORIES_BinOpBS" }, { "name": "BoolOp", "desc": "Boolean operations e.g. and or", "operations": [ "ast.And", "ast.Or" ], "category": "CATEGORIES_BoolOp" }, { "name": "Compare", "desc": "Comparison operations e.g. == >= <= > <", "operations": [ "ast.Eq", "ast.NotEq", "ast.Lt", "ast.LtE", "ast.Gt", "ast.GtE" ], "category": "CATEGORIES_Compare" }, { "name": "Compare In", "desc": "Compare membership e.g. in, not in", "operations": [ "ast.In", "ast.NotIn" ], "category": "CATEGORIES_CompareIn" }, { "name": "Compare Is", "desc": "Comapre identity e.g. is, is not", "operations": [ "ast.Is", "ast.IsNot" ], "category": "CATEGORIES_CompareIs" }, { "name": "If", "desc": "If statement tests e.g. original statement, True, False", "operations": [ "If_True", "If_False", "If_Statement" ], "category": "CATEGORIES_If" }, { "name": "Index", "desc": "Index values for iterables e.g. i[-1], i[0], i[0][1]", "operations": [ "Index_NumPos", "Index_NumNeg", "Index_NumZero" ], "category": "CATEGORIES_Index" }, { "name": "NameConstant", "desc": "Named constant mutations e.g. True, False, None", "operations": [ true, false, null ], "category": "CATEGORIES_NameConstant" }, { "name": "Slice Unbounded Swap", "desc": "Slice mutations to swap lower/upper values, x[2:] (unbound upper) to x[:2], (unbound lower). Steps are not changed.", "operations": [ "Slice_UnboundUpper", "Slice_UnboundLower", "Slice_Unbounded" ], "category": "CATEGORIES_SliceUS" } ] } ``` ``` -------------------------------- ### Prepare for Mutation: Reset and Filter - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Resets the genome to a specific source file ('a.py') and filters its targets to include only 'BinOp' (binary operation) codes. This prepares the genome for targeted mutation. ```python # Set the Genome back to example a # filter to only the BinOp targets genome.source_file = src_loc / "a.py" genome.filter_codes = ("bn",) ``` -------------------------------- ### Get Valid Codes - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Retrieves all potential valid codes available in the catcode_filter. This is useful for understanding the scope of possible code identifiers. ```python catcode_filter.valid_codes ``` -------------------------------- ### Accessing Mutation Targets and Covered Targets in Genome Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Demonstrates how to access the `targets` and `covered_targets` properties of a `Genome` object. These properties return sets of `LocIndex` objects representing AST locations that can be mutated. `covered_targets` specifically includes locations with coverage information. ```python genome.targets ``` ```python # Example output for genome.targets: # {LocIndex(ast_class='BinOp', lineno=6, col_offset=11, op_type=, end_lineno=6, end_col_offset=16), # LocIndex(ast_class='Compare', lineno=10, col_offset=11, op_type=, end_lineno=10, end_col_offset=16)} ``` ```python genome.covered_targets ``` ```python # Example output for genome.covered_targets: # {LocIndex(ast_class='BinOp', lineno=6, col_offset=11, op_type=, end_lineno=6, end_col_offset=16)} ``` ```python # Finding targets not covered by coverage genome.targets - genome.covered_targets ``` ```python # Example output for uncovered targets: # {LocIndex(ast_class='Compare', lineno=10, col_offset=11, op_type=, end_lineno=10, end_col_offset=16)} ``` -------------------------------- ### NameConstant Mutations - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Shows mutations for named constants like `True`, `False`, and `None`. The example `x = True` can be mutated to `x = False` or `x = None`. ```Python # source code x = True # mutations x = False X = None ``` -------------------------------- ### Accessing the Abstract Syntax Tree (AST) of a Genome Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Explains how to access the Abstract Syntax Tree (AST) of a source file through the `ast` property of the `Genome` object. This property provides access to the root of the AST, allowing inspection of its structure, including the body of the module and the properties of individual AST nodes. ```python genome.ast ``` ```python # Example output for genome.ast: # <_ast.Module object at 0x...> ``` ```python genome.ast.body ``` ```python # Example output for genome.ast.body: # [, , ...] ``` ```python genome.ast.body[1].__dict__ ``` ```python # Example output for properties of an AST node (e.g., FunctionDef): # {'name': 'add_five', 'args': <_ast.arguments object at ...>, 'body': [], 'decorator_list': [], 'returns': None, 'type_comment': None, 'lineno': 5, 'col_offset': 0, 'end_lineno': 6, 'end_col_offset': 16} ``` -------------------------------- ### Get CLI Help Epilog Text Source: https://mutatest.readthedocs.io/en/latest/modules Provides the epilog text to be displayed at the end of the Mutatest CLI help message. This can include additional usage information or notes. ```python def cli_epilog() -> str: """Epilog for the help output. """ # Placeholder for actual implementation pass ``` -------------------------------- ### Get Genome Group (Python) Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/run Retrieves a GenomeGroup based on a source location and configuration. It handles both single files and directories, applying filters and exclusions as specified in the config. ```python from pathlib import Path # Assuming GenomeGroup, Config, LOGGER, and colorize_output are defined/imported def get_genome_group(src_loc: Path, config: Config) -> GenomeGroup: """Get the ``GenomeGroup`` based on ``src_loc`` and ``config``. ``Config`` is used to set global filter codes and exclude files on group creation. Args: src_loc: Path, can be directory or file config: the running config object Returns: ``GenomeGroup`` based on ``src_loc`` and config. """ ggrp = GenomeGroup() # check if src_loc is a single file, otherwise assume it's a directory if src_loc.is_file(): ggrp.add_file(source_file=src_loc) else: ggrp.add_folder( source_folder=src_loc, exclude_files=config.exclude_files, ignore_test_files=True ) if config.filter_codes: LOGGER.info("Category restriction, chosen categories: %s", sorted(config.filter_codes)) ggrp.set_filter(filter_codes=config.filter_codes) for k, genome in ggrp.items(): LOGGER.info( "%s", colorize_output( f"{len(genome.targets)} mutation targets found in {genome.source_file} AST.", "green" if len(genome.targets) > 0 else "yellow", ), ) for e in config.exclude_files: LOGGER.info("%s", colorize_output(f"{e.resolve()} excluded.", "yellow")) return ggrp ``` -------------------------------- ### Configuration and Utilities Source: https://mutatest.readthedocs.io/en/latest/modules Utilities for managing run configurations, output formatting, and capturing output. ```APIDOC ## GET /run/config ### Description Retrieves the current run configuration object. ### Method GET ### Endpoint /run/config ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **Config** (mutatest.run.Config) - The configuration object for mutation trials. #### Response Example ```json { "n_locations": 0, "exclude_files": [], "filter_codes": [], "random_seed": null, "break_on_survival": false, "break_on_detected": false, "break_on_error": false, "break_on_unknown": false, "break_on_timeout": false, "ignore_coverage": false, "max_runtime": 10.0, "multi_processing": false } ``` ## POST /run/config ### Description Sets or updates the run configuration for mutation trials. ### Method POST ### Endpoint /run/config ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **n_locations** (int) - Optional. Number of locations to mutate. - **exclude_files** (List[pathlib.Path]) - Optional. List of files to exclude. - **filter_codes** (List[str]) - Optional. List of filter codes. - **random_seed** (Optional[int]) - Optional. Seed for random number generation. - **break_on_survival** (bool) - Optional. Break on survival. - **break_on_detected** (bool) - Optional. Break on detected. - **break_on_error** (bool) - Optional. Break on error. - **break_on_unknown** (bool) - Optional. Break on unknown. - **break_on_timeout** (bool) - Optional. Break on timeout. - **ignore_coverage** (bool) - Optional. Ignore coverage. - **max_runtime** (float) - Optional. Maximum runtime for trials. - **multi_processing** (bool) - Optional. Enable multi-processing. ### Request Example ```json { "max_runtime": 30.0, "multi_processing": true } ``` ### Response #### Success Response (200) - **message** (str) - Confirmation message. #### Response Example ```json { "message": "Configuration updated successfully." } ``` ## POST /run/capture_output ### Description Utility function to determine if output should be captured based on the log level. ### Method POST ### Endpoint /run/capture_output ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **log_level** (int) - The logging level (e.g., 10 for DEBUG). ### Request Example ```json { "log_level": 20 } ``` ### Response #### Success Response (200) - **capture** (bool) - True if output should be captured, False otherwise. #### Response Example ```json { "capture": true } ``` ## POST /run/colorize_output ### Description Colorizes a given string output with a specified terminal color. ### Method POST ### Endpoint /run/colorize_output ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **output** (str) - The string to colorize. - **color** (str) - The color to use ('red' or 'green'). ### Request Example ```json { "output": "Mutation failed!", "color": "red" } ``` ### Response #### Success Response (200) - **colorized_output** (str) - The colorized string, or the original string if the color is invalid. #### Response Example ```json { "colorized_output": "\033[91mMutation failed!\033[0m" } ``` ``` -------------------------------- ### Get Valid Categories - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Retrieves a mapping of valid category names to their corresponding codes. This helps in understanding which codes are associated with specific AST node types or operations. ```python catcode_filter.valid_categories ``` -------------------------------- ### Discard Code and View Mutations - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Shows how to remove a code from the active set and then re-evaluates the available mutations. This illustrates the impact of code removal on mutation possibilities. ```python # discard codes catcode_filter.discard_code("aa") catcode_filter.codes catcode_filter.valid_mutations ``` -------------------------------- ### Slice Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Illustrates slice mutations, such as changing `x[:2]` to `x[2:]` or swapping bounds when `None` is involved. `Slice_UnboundedUpper` mutates the upper bound to be unbounded. ```Python # source code w = a[:2] x = a[4:] # mutation w = a[2:] # Slice_UnboundedUpper, upper is now unbounded and lower has a value x = a[4:] ``` -------------------------------- ### View Valid Mutations - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Displays all possible mutations that can be applied based on the currently set codes. This provides insight into the types of code transformations Mutatest can perform. ```python # see all validation mutations # based on the set codes catcode_filter.valid_mutations ``` -------------------------------- ### AugAssign Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Demonstrates augmented assignment mutations such as +=, -=, *=, and /=. The original code `x += y` can be mutated to `x -= y`, `x *= y`, or `x /= y`. ```Python # source code x += y # mutations x -= y # AugAssign_Sub x *= y # AugAssign_Mult x /= y # AugAssign_Div ``` -------------------------------- ### Run Single Mutation Trial - Python Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Executes a single mutation trial using the `run.create_mutation_run_trial` function. This applies a specified mutation to a target and runs tests, returning the trial result. ```python # Alternatively, use run to do a single trial # and return the result mutant_trial_result = run.create_mutation_run_trial( genome, mutation_target, ast.Mult, ["pytest"], max_runtime=5 ) ``` -------------------------------- ### Main CLI Entry Point Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/cli The primary entry point for the Mutatest command-line tool. It first checks cache invalidation status, then parses command-line arguments, and finally calls the main mutation testing function. ```python import sys # Assume cache and main are defined elsewhere # from .cache import check_cache_invalidation_mode # from .core import main def cli_main() -> None: """Entry point to run CLI args and execute main function.""" # Run a quick check at the beginning in case of later OS errors. cache.check_cache_invalidation_mode() # Assuming cache.check_cache_invalidation_mode() performs a check args = cli_args(sys.argv[1:]) # Calls the argument parsing function main(args) # Calls the main mutation testing function with parsed arguments ``` -------------------------------- ### Get Mutation Sample Space (Python) Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/run Retrieves the sample space for mutation trials, prioritizing covered targets unless coverage is ignored or unavailable. It returns a sorted list of targets. ```python from pathlib import Path from typing import List from operator import attrgetter # Assuming GenomeGroup and GenomeGroupTarget are defined elsewhere # Assuming LOGGER is configured for logging 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) ``` -------------------------------- ### Get Source Location - Python Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/cli Determines the source code location for mutation testing. If a location is not provided, it attempts to automatically find the first package. Raises a FileNotFoundError if no source location can be determined. ```python def get_src_location(src_loc: Optional[Path] = None) -> Path: """Find packages is used if the ``src_loc`` is not set Args: src_loc: current source location, defaults to None Returns: Path to the source location Raises: FileNoeFoundError: if the source location doesn't exist. """ if not src_loc: find_pkgs = find_packages() if find_pkgs: src_loc = Path(find_pkgs[0]) return src_loc else: if src_loc.exists(): return src_loc raise FileNotFoundError( "No source directory specified or automatically detected. " "Use --src or --help to see options." ) ``` -------------------------------- ### Set Coverage File for GenomeGroup Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Demonstrates setting a coverage file for an entire GenomeGroup, which then filters the targets to only those covered by the specified file. This helps in analyzing mutation targets within the context of actual test coverage. ```python # You can set a filter or # coverage file for the entire set # of genomes ggrp.set_coverage = Path(".coverage") for t in ggrp.covered_targets: print( t.source_path, t.loc_idx ) ``` -------------------------------- ### Get Mutations for Target (Python) Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/transformers Given a target location index, this function identifies all potential mutations that can be applied based on the Abstract Syntax Tree (AST) definitions. It serves to determine the possible transformations for a specific part of the code. ```python import ast from typing import Set, Any # Assuming LocIndex is defined elsewhere, e.g.: class LocIndex: def __init__(self, filename: str, lineno: int, col_offset: int): self.filename = filename self.lineno = lineno self.col_offset = col_offset 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 (filename, line number, column offset) of the target code. Returns: A set of applicable mutation types for the given target. """ # This is a placeholder for the actual implementation. # The real implementation would involve parsing the AST of the target code # and comparing it against the defined mutation operation sets. applicable_mutations: Set[Any] = set() # Example: if target node is an ast.BinOp, add BinOp related mutations # if target node is ast.Compare, add Compare related mutations # ... and so on for all AST node types and custom mutations. return applicable_mutations ``` -------------------------------- ### Specify Source Files and Test Commands Source: https://mutatest.readthedocs.io/en/latest/commandline Enables targeting specific source files and their corresponding test files for mutation testing. This is useful for focused testing within a larger package. Supports both long and short argument forms. ```bash $ mutatest --src mypackage/run.py --testcmds "pytest tests/test_run.py" ``` ```bash # using shorthand arguments $ mutatest -s mypackage/run.py -t "pytest tests/test_run.py" ``` -------------------------------- ### mutatest.cli.cli_main Source: https://mutatest.readthedocs.io/en/latest/modules The main entry point for the Mutatest CLI. It handles parsing arguments and executing the primary mutation testing routine. ```APIDOC ## POST /cli/main ### Description Entry point to run CLI args and execute the main mutation testing function. ### Method POST ### Endpoint /cli/main ### Response #### Success Response (200) - **None** - Indicates successful execution. ``` -------------------------------- ### Index Mutations Example - Python Source: https://mutatest.readthedocs.io/en/latest/mutants Demonstrates mutations to index values within iterables. Positive indices can be mutated to `Index_NumPos`, negative to `Index_NumNeg`, and zero indices to `Index_NumZero`. Mutations can also involve changing the index to 0, 1, or -1. ```Python # source code x = [a[10], a[-4], a[0]] # mutations x = [a[-1], a[-4], a[0]] # a[10] mutated to Index_NumNeg x = [a[10], a[0], a[0]] # a[-4] mutated to Index_NumZero x = [a[10], a[1], a[0]] # a[-4] mutated to Index_NumPos x = [a[10], a[-4], a[1]] # a[0] mutated to Index_NumPos ``` -------------------------------- ### Get Status Summary Dictionary Source: https://mutatest.readthedocs.io/en/latest/_modules/mutatest/report Calculates a summary of mutant trial statuses and returns it as a dictionary. It counts the occurrences of each status (e.g., DETECTED, TIMEOUT, SURVIVED) and adds the total number of runs and the current execution time. This dictionary is intended for use in formatting the final report. ```python 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 ``` -------------------------------- ### Display contents of b.py Source: https://mutatest.readthedocs.io/en/latest/api_tutorial/api_tutorial Reads and prints the content of the 'b.py' file. This file contains a function 'is_match' that checks for equality using the 'is' operator. The output shows the source code of this function. ```python # Contents of b.py example source file open_print(src_loc / "b.py") ```