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:
- 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:
- Returns:
A tuple containing a boolean indicating if the process was killed, the process’s return code, and the process’s stdout.
- Return type:
- 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.
- 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:
- 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:
- Returns:
A dictionary mapping method names to a list containing the mutant density, cyclomatic complexity, and lines of code.
- Return type:
- 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-
.
- 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--
.
- 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-
.
- 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-=
.
- 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 witha
.
- 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||
.
- 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.
- countMutants(metaTypes: List[str] = ['Traditional'])[source]
Counts the number of mutants for each mutation operator type.
- gatherHigherOrderMutants(higherOrderDirective: int, metaTypes: List[str] = ['Traditional'])[source]
Gathers all mutants and creates higher-order mutants.
- gatherMutants(metaTypes: List[str] = ['Traditional'])[source]
Gathers all mutants of the specified meta types.
- 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|
.
- 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.
- 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.
- 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.
- 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
.
- 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 withnull
.
- 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;
.
- 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<=
.
- 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 withreturn 0;
.
- 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
orfalse
. For example,if (x != null)
will be replaced withif (true)
.
- 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>>
.
- 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.
- 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.
- 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:
- 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:
- 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:
- 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:
- getMethodNameForNode(tree: CompilationUnitContext, nodeIndex: int)[source]
Gets the name of the method that contains the node with the specified index.
- 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:
- 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:
- 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:
- 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
- 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
- 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.
- 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.
- littledarwin.License.returnLicense()[source]
Returns the license text.
- Returns:
The license text.
- Return type:
- 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.