API Reference

This module is the main entry point for the LittleDarwin mutation analysis framework. It contains the logic for parsing command-line arguments, running the mutation phase, and running the build phase.

littledarwin.LittleDarwin.buildPhase(options)[source]

Performs the build phase of LittleDarwin.

This function iterates through the mutants in the database, and for each mutant, it replaces the original file with the mutant, runs the build command, and records whether the build succeeded or failed. It then generates a report of the results.

Parameters:

options (optparse.Values) – The command-line options.

littledarwin.LittleDarwin.main(mockArgs: list = None)[source]

The main entry point for the LittleDarwin application.

This function parses the command-line arguments and then calls the appropriate functions to perform the mutation and/or build phases.

Parameters:

mockArgs (list, optional) – A list of command-line arguments for testing purposes. If None, the arguments are read from sys.argv.

littledarwin.LittleDarwin.mutationPhase(options, filterType, filterList, higherOrder)[source]

Performs the mutation phase of LittleDarwin.

This function finds all the Java files in the source directory, parses them, generates mutants, and stores them in a database.

Parameters:
  • options (optparse.Values) – The command-line options.

  • filterType (str) – The type of filter to use (“whitelist” or “blacklist”).

  • filterList (list) – A list of files or packages to include or exclude.

  • higherOrder (int) – The order of mutation to perform.

littledarwin.LittleDarwin.parseCmdArgs(optionParser: OptionParser, mockArgs: list = None) object[source]

Parses the command-line arguments for LittleDarwin.

Parameters:
  • optionParser (optparse.OptionParser) – The OptionParser instance to use.

  • mockArgs (list, optional) – A list of command-line arguments for testing purposes. If None, the arguments are read from sys.argv.

Returns:

A tuple containing the parsed options, the filter type, the filter list, and the higher-order mutation value.

Return type:

tuple

littledarwin.LittleDarwin.timeoutAlternative(commandString, workingDirectory, timeout, inputData=None)[source]

Runs a command with a timeout, and kills it if it takes too long.

This function uses a watchdog thread to kill the process if the timeout expires. It is used to prevent the build process from hanging.

Parameters:
  • commandString (list) – The command to run, as a list of strings.

  • workingDirectory (str) – The directory in which to run the command.

  • timeout (int) – The timeout in seconds.

  • inputData (bytes, optional) – Input data to pass to the process’s stdin.

Returns:

A tuple containing a boolean indicating if the process was killed, the process’s return code, and the process’s stdout.

Return type:

tuple

class littledarwin.JavaIO.JavaIO(verbose=False)[source]

This class handles all the file I/O operations for LittleDarwin, such as finding Java files, reading their content, and writing the mutated files to disk.

filterFiles(mode='blacklist', filterList=None)[source]

Filters the list of files based on a whitelist or blacklist.

Parameters:
  • mode (str) – The filter mode, either “whitelist” or “blacklist”.

  • filterList (list) – A list of package names or file paths to filter by.

generateNewFile(originalFile=None, fileData=None, mutantsPerLine=None, densityReport=None, aggregateComplexity=None)[source]

Generates a new file containing a mutant.

This function creates a new directory for the mutated file, copies the original file to that directory, and then writes the mutated code to a new file in that directory. It also writes out a number of reports about the mutation.

Parameters:
  • originalFile (str) – The path to the original file.

  • fileData (str) – The content of the mutated file.

  • mutantsPerLine (dict) – A dictionary mapping line numbers to the number of mutants on that line.

  • densityReport (str) – The HTML report of the mutant density.

  • aggregateComplexity (dict) – A dictionary containing the aggregate complexity report for the class.

Returns:

The relative path to the new file.

Return type:

str

getAggregateComplexityReport(mutantDensityPerMethod: Dict[str, int], cyclomaticComplexityPerMethod: Dict[str, int], linesOfCodePerMethod: Dict[str, int]) Dict[str, List[int]][source]

Aggregates complexity metrics for each method in a class.

Parameters:
  • mutantDensityPerMethod (dict) – A dictionary mapping method names to the number of mutants in that method.

  • cyclomaticComplexityPerMethod (dict) – A dictionary mapping method names to their cyclomatic complexity.

  • linesOfCodePerMethod (dict) – A dictionary mapping method names to their lines of code.

Returns:

A dictionary mapping method names to a list containing the mutant density, cyclomatic complexity, and lines of code.

Return type:

dict

getFileContent(filePath=None)[source]

Reads the content of a file and returns it as a string.

Parameters:

filePath (str) – The path to the file.

Returns:

The content of the file.

Return type:

str

listFiles(targetPath=None, buildPath=None, filterList=None, filterType='blacklist', desiredType='*.java')[source]

Lists all the files in a directory that match a given type, and optionally filters them.

Parameters:
  • targetPath (str) – The path to the source files.

  • buildPath (str) – The path to the build directory.

  • filterList (list) – A list of package names or file paths to filter by.

  • filterType (str) – The filter mode, either “whitelist” or “blacklist”.

  • desiredType (str) – The type of files to list (e.g., “*.java”).

class littledarwin.JavaMutate.ArithmeticOperatorReplacementBinary(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces binary arithmetic operators. For example, + is replaced with -.

filterCriteria()[source]

Filters the expression nodes to include only those that are binary arithmetic operations.

generateMutants()[source]

Generates mutants by replacing the binary arithmetic operators.

class littledarwin.JavaMutate.ArithmeticOperatorReplacementShortcut(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces shortcut arithmetic operators. For example, ++ is replaced with --.

filterCriteria()[source]

Filters the expression nodes to include only those that are shortcut arithmetic operations.

generateMutants()[source]

Generates mutants by replacing the shortcut arithmetic operators.

class littledarwin.JavaMutate.ArithmeticOperatorReplacementUnary(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces unary arithmetic operators. For example, a unary + is replaced with a unary -.

filterCriteria()[source]

Filters the expression nodes to include only those that are unary arithmetic operations.

generateMutants()[source]

Generates mutants by replacing the unary arithmetic operators.

class littledarwin.JavaMutate.AssignmentOperatorReplacementShortcut(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces shortcut assignment operators. For example, += is replaced with -=.

filterCriteria()[source]

Filters the expression nodes to include only those that are shortcut assignment operations.

generateMutants()[source]

Generates mutants by replacing the shortcut assignment operators.

class littledarwin.JavaMutate.ConditionalOperatorDeletion(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator deletes conditional operators. For example, !a is replaced with a.

filterCriteria()[source]

Filters the expression nodes to include only those that are conditional operations.

generateMutants()[source]

Generates mutants by deleting the conditional operators.

class littledarwin.JavaMutate.ConditionalOperatorReplacement(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces conditional operators. For example, && is replaced with ||.

filterCriteria()[source]

Filters the expression nodes to include only those that are conditional operations.

generateMutants()[source]

Generates mutants by replacing the conditional operators.

class littledarwin.JavaMutate.JavaMutate(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, verbose: bool = False)[source]

This class is the main entry point for the mutation of a Java source file. It takes a parse tree and the original source code, and then uses a collection of mutation operators to generate a list of mutants.

aggregateReport(littleDarwinVersion: str)[source]

Generates an HTML report of all mutations for a file.

Parameters:

littleDarwinVersion (str) – The version of LittleDarwin.

Returns:

An HTML report of all mutations for a file.

Return type:

str

countMutants(metaTypes: List[str] = ['Traditional'])[source]

Counts the number of mutants for each mutation operator type.

Parameters:

metaTypes (list) – The types of mutation operators to use.

Returns:

A dictionary mapping mutation operator types to the number of mutants.

Return type:

dict

property cssStyle

Returns CSS Style for the aggregate report

Returns:

CSS Style

Return type:

str

gatherHigherOrderMutants(higherOrderDirective: int, metaTypes: List[str] = ['Traditional'])[source]

Gathers all mutants and creates higher-order mutants.

Parameters:
  • higherOrderDirective (int) – The requested higher-order order.

  • metaTypes (list) – The type of mutation operators to use.

Returns:

A tuple containing a list of mutated source code and a dictionary mapping mutation operator types to the number of mutants.

Return type:

tuple

gatherMutants(metaTypes: List[str] = ['Traditional'])[source]

Gathers all mutants of the specified meta types.

Parameters:

metaTypes (list) – The types of mutation operators to use.

Returns:

A tuple containing a list of mutated source code and a dictionary mapping mutation operator types to the number of mutants.

Return type:

tuple

instantiateMutationOperators(metaTypes: List[str] = ['Traditional'], generateMutants: bool = True)[source]

Instantiates all mutation operators of the specified meta types.

Parameters:
  • metaTypes (list) – A list of meta types to instantiate.

  • generateMutants (bool) – A boolean indicating whether to generate mutants.

class littledarwin.JavaMutate.LogicalOperatorReplacement(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces logical operators. For example, & is replaced with |.

filterCriteria()[source]

Filters the expression nodes to include only those that are logical operations.

generateMutants()[source]

Generates mutants by replacing the logical operators.

class littledarwin.JavaMutate.Mutant(mutantID: int, mutationList: List[Mutation], sourceCode: str)[source]

This class represents a mutant, which is a version of the source code that has been modified by one or more mutations. It contains a list of mutations and the original source code, and it can be used to generate the mutated source code.

getLine(lineNumber: int, code: str = None) str[source]

Gets a specific line from the source code.

Parameters:
  • lineNumber (int) – The line number to get.

  • code (str, optional) – The code to get the line from. If None, the original source code is used.

Returns:

The specified line of code.

Return type:

str

mutateCode()[source]

Applies the mutations in the mutation list to the source code to generate the mutated code.

property stub: str

Generates the text stub that goes in the beginning of each mutant file.

Returns:

Returns text stub on top of each mutant

Return type:

str

class littledarwin.JavaMutate.Mutation(startPos: int, endPos: int, lineNumber: int, nodeID: int, mutatorType: str, replacementText: str, color: str = '#FFFFFF')[source]

This class represents a single mutation, which is a change to a small section of the source code. It contains information about the location of the mutation, the type of mutator used, and the text to replace the original code with.

applyMutation(sourceCode: str, byteOffset: int = 0) str[source]

Applies the mutation to the given source code.

Parameters:
  • sourceCode (str) – The source code to apply the mutation to.

  • byteOffset (int) – The byte offset to apply to the start and end positions. This is used when applying multiple mutations to the same file.

Returns:

The mutated source code.

Return type:

str

property byteOffset: int

Returns the byte offset introduced by the mutation.

Returns:

byte offset introduced by the mutation

Return type:

int

isInRange(start, end)[source]

Checks if the mutation is within the given range.

Parameters:
  • start (int) – The start of the range.

  • end (int) – The end of the range.

Returns:

True if the mutation is within the range, False otherwise.

Return type:

bool

class littledarwin.JavaMutate.MutationOperator(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants=True)[source]

This is a base class for all mutation operators. A mutation operator is a class that knows how to find specific nodes in a parse tree and generate mutants from them.

property cssClass

Returns CSS Class for the mutation operator

Returns:

CSS Class

Return type:

str

filterCriteria()[source]

Filters out the nodes that do not match the input critera

findNodes()[source]

Finds all nodes that match the search criteria

generateMutants()[source]

Generates the mutants

class littledarwin.JavaMutate.NullifyInputVariable(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator nullifies input variables to a method by adding a statement at the beginning of the method to set the variable to null.

filterCriteria()[source]

Filters the method declaration nodes to include only those with non-primitive input variables.

findNodes()[source]

Finds all method declaration nodes in the parse tree.

generateMutants()[source]

Generates mutants by adding a statement to nullify each non-primitive input variable.

class littledarwin.JavaMutate.NullifyObjectInitialization(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator nullifies object initializations by replacing them with null. For example, new Foo() will be replaced with null.

filterCriteria()[source]

Filters the creator nodes to include only those that are object initializations.

findNodes()[source]

Finds all creator nodes in the parse tree.

generateMutants()[source]

Generates mutants by replacing the object initialization with null.

class littledarwin.JavaMutate.NullifyReturnValue(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator nullifies the return value of a method by replacing the return statement with return null;.

filterCriteria()[source]

Filters the terminal nodes to include only those that are ‘return’ statements with a non-primitive return type.

findNodes()[source]

Finds all terminal nodes in the parse tree.

generateMutants()[source]

Generates mutants by replacing the return statement with “return null;”.

class littledarwin.JavaMutate.RelationalOperatorReplacement(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces relational operators. For example, > is replaced with <=.

filterCriteria()[source]

Filters the expression nodes to include only those that are relational operations.

generateMutants()[source]

Generates mutants by replacing the relational operators.

class littledarwin.JavaMutate.RemoveMethod(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator removes the body of a method and replaces it with a default return value. For example, a method that returns an int will be replaced with return 0;.

filterCriteria()[source]

Filters the found method bodies to include only those with a valid return type. It also filters out simple getters and setters and methods/constructors with @Inject annotation.

findNodes()[source]

Finds all method and constructor bodies in the parse tree.

generateMutants()[source]

Generates mutants by replacing the method body with a default return value based on the method’s return type.

class littledarwin.JavaMutate.RemoveNullCheck(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator removes null checks by replacing them with true or false. For example, if (x != null) will be replaced with if (true).

filterCriteria()[source]

Filters the expression nodes to include only those that are null checks.

findNodes()[source]

Finds all expression nodes in the parse tree.

generateMutants()[source]

Generates mutants by replacing the null check with true or false.

class littledarwin.JavaMutate.ShiftOperatorReplacement(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

This mutation operator replaces shift operators. For example, << is replaced with >>.

filterCriteria()[source]

Filters the expression nodes to include only those that are shift operations.

generateMutants()[source]

Generates mutants by replacing the shift operators.

class littledarwin.JavaMutate.TraditionalMutationOperator(sourceTree: CompilationUnitContext, sourceCode: str, javaParseObject: JavaParse, generateMutants: bool = True)[source]

A base class for all traditional mutation operators. These operators perform simple mutations, such as replacing one operator with another.

filterCriteriaBinaryExpression(node: ExpressionContext, symbolList: List[str])[source]

A helper method to filter binary expressions based on a list of symbols. :param node: The expression node to check. :param symbolList: A list of symbols to match. :return: True if the node is a binary expression with a matching symbol, False otherwise.

filterCriteriaUnaryExpression(node: ExpressionContext, symbolList: List[str])[source]

A helper method to filter unary expressions based on a list of symbols. :param node: The expression node to check. :param symbolList: A list of symbols to match. :return: True if the node is a unary expression with a matching symbol, False otherwise.

findNodes()[source]

Finds all expression nodes in the parse tree.

generateMutantsBinaryExpression(node: ExpressionContext, symbolDict: dict, id: int)[source]

A helper method to generate mutants for binary expressions. :param node: The expression node to mutate. :param symbolDict: A dictionary mapping original symbols to their replacements. :param id: The ID of the mutant. :return: A Mutant object.

generateMutantsUnaryExpression(node: ExpressionContext, symbolDict: dict, id: int)[source]

A helper method to generate mutants for unary expressions. :param node: The expression node to mutate. :param symbolDict: A dictionary mapping original symbols to their replacements. :param id: The ID of the mutant. :return: A Mutant object.

littledarwin.JavaMutate.getAllInstantiableSubclasses(parentClass)[source]

Gets all instantiable subclasses of a given class. :param parentClass: the class that all its subclasses must be returned :return: set of MutationOperator instantiable subclasses

class littledarwin.JavaParse.JavaParse(verbose=False)[source]

This class uses ANTLR4 to parse Java source code. It provides methods for traversing and analyzing the parse tree, such as finding nodes of a specific type, getting the cyclomatic complexity of a method, and getting the name of the method that contains a specific node.

distance(tree, node1, node2)[source]

Calculates the distance between two nodes in the parse tree.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • node1 (int) – The index of the first node.

  • node2 (int) – The index of the second node.

Returns:

The distance between the two nodes, or -1 if they are not in the same subtree.

Return type:

int

getCyclomaticComplexity(methodBody) int[source]

Calculates the cyclomatic complexity of a method.

Parameters:

methodBody (antlr4.tree.Tree.ParseTree) – The MethodBodyContext or ConstructorBodyContext of the method.

Returns:

The cyclomatic complexity of the method.

Return type:

int

getCyclomaticComplexityAllMethods(tree) Dict[str, int][source]

Calculates the cyclomatic complexity for all methods in the parse tree.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

Returns:

A dictionary mapping method names to their cyclomatic complexity.

Return type:

dict

getInMethodLines(tree: CompilationUnitContext) list[source]

Gets a list of all line numbers that are within a method.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

Returns:

A sorted list of line numbers.

Return type:

list

getLinesOfCodePerMethod(tree: CompilationUnitContext) dict[source]

Gets the number of lines of code for each method in the parse tree.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

Returns:

A dictionary mapping method names to the number of lines of code.

Return type:

dict

getMethodNameForNode(tree: CompilationUnitContext, nodeIndex: int)[source]

Gets the name of the method that contains the node with the specified index.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • nodeIndex (int) – The index of the node.

Returns:

The name of the method, or “*not in a method*” if the node is not in a method.

Return type:

str

getMethodRanges(tree: CompilationUnitContext) dict[source]

Gets the start and end character indices for each method in the parse tree.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

Returns:

A dictionary mapping method names to a tuple of (start, stop) character indices.

Return type:

dict

getMethodTypeForNode(node)[source]

Gets the return type of the method that contains the specified node.

Parameters:

node (antlr4.tree.Tree.ParseTree) – The node to check.

Returns:

The return type of the method, or None if the node is not in a method.

Return type:

str

getNode(tree, index)[source]

Gets a node from the parse tree by its index.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • index (int) – The index of the node to get.

Returns:

The node with the specified index, or None if the node is not found.

Return type:

antlr4.tree.Tree.ParseTree

getText(tree: RuleContext)[source]

Gets the text of a node and all its children.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the node.

Returns:

A string containing the text of the node and its children.

Return type:

str

numerify(tree)[source]

Adds a unique nodeIndex to each node in the parse tree. This is used to identify nodes when creating mutations.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

parse(fileContent)[source]

Parses the given Java source code and returns a parse tree.

Parameters:

fileContent (str) – A string containing the Java source code.

Returns:

A parse tree representing the Java source code.

Return type:

antlr4.tree.Tree.ParseTree

seek(tree, type)[source]

DEPRECATED. Finds all nodes of a specific type in the parse tree.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • type (type) – The type of node to search for.

Returns:

A list of node indices of the specified type.

Return type:

list

seekAllNodes(tree, nodeType)[source]

Finds all nodes of a specific type in the parse tree.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • nodeType (type) – The type of node to search for.

Returns:

A list of nodes of the specified type.

Return type:

list

seekFirstMatchingParent(node, nodeType)[source]

Finds the first parent of a node that matches the specified type.

Parameters:
  • node (antlr4.tree.Tree.ParseTree) – The node to start the search from.

  • nodeType (type) – The type of parent node to search for.

Returns:

The first matching parent node, or None if no matching parent is found.

Return type:

antlr4.tree.Tree.ParseTree

seekNode(tree, nodeIndex)[source]

Finds a node in the parse tree by its index.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • nodeIndex (int) – The index of the node to find.

Returns:

The depth of the node in the tree, or None if the node is not found.

Return type:

int

setNode(tree, index, node)[source]

Sets a node in the parse tree at a specific index.

Parameters:
  • tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

  • index (int) – The index of the node to set.

  • node (antlr4.tree.Tree.ParseTree) – The new node.

toString(tree)[source]

Prints the text of all nodes in the parse tree.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

tree2DOT(tree)[source]

Converts a parse tree to a DOT representation for visualization with Graphviz.

Parameters:

tree (antlr4.tree.Tree.ParseTree) – The root of the parse tree.

Returns:

A Graphviz Digraph object, or None if Graphviz is not installed.

Return type:

graphviz.Digraph

class littledarwin.JavaParse.LittleDarwinErrorStrategy[source]

This class is a custom error strategy for the ANTLR4 parser. It is used to handle parsing errors by throwing an exception, which allows the file to be safely ignored.

recover(parser: Parser, exception: RecognitionException)[source]

This method is called when the parser encounters a syntax error.

Parameters:
  • parser (antlr4.Parser) – The parser that encountered the error.

  • exception (antlr4.RecognitionException) – The recognition exception.

littledarwin.License.outputLicense()[source]

Prints the license text to stdout.

littledarwin.License.returnLicense()[source]

Returns the license text.

Returns:

The license text.

Return type:

str

class littledarwin.ReportGenerator.ReportGenerator(littleDarwinVersion=None)[source]

This class generates the HTML reports for LittleDarwin. It creates a summary report for the entire project, as well as detailed reports for each file that was mutated.

generateHTMLFinalReport(resultData, reportPath)[source]

Generates the final HTML report for the entire project.

Parameters:
  • resultData (list) – A list of lists, where each inner list contains the file path, the number of survived mutants, and the total number of mutants for a file.

  • reportPath (str) – The path to the report file.

Returns:

The HTML report as a string.

Return type:

str

generateHTMLReportPerFile(filePath, reportPath, survived, killed)[source]

Generates an HTML report for a single file.

Parameters:
  • filePath (str) – The path to the file.

  • reportPath (str) – The path to the report file.

  • survived (list) – A list of the names of the survived mutants.

  • killed (list) – A list of the names of the killed mutants.

Returns:

The HTML report as a string.

Return type:

str

initiateDatabase(databasePath)[source]

Initiates the results database.

Parameters:

databasePath (str) – The path to the results database.