diff --git a/afluent/__init__.py b/afluent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46e5712ecd0fbfc82db79017d83cee782d123e2b --- /dev/null +++ b/afluent/__init__.py @@ -0,0 +1,3 @@ +"""standard init file.""" + +__version__ = "0.1.0" diff --git a/afluent/line.py b/afluent/line.py new file mode 100644 index 0000000000000000000000000000000000000000..9710fc4ea01b6eeb240cab3023eb693b5b236165 --- /dev/null +++ b/afluent/line.py @@ -0,0 +1,211 @@ +"""Create object oriented structure to keep track of line information.""" + +import math +from typing import List + +# Scores: +TARAN = "tarantula" +OCHIAI = "ochiai" +OCHIAI2 = "ochiai2" +DSTAR = "dstar" + + +# Tiebreakers +RANDOM = "random" +CYCLOMATIC = "cyclomatic" +LOGICAL = "logical" +ENHANCED = "enhanced" + + +# pylint: disable=R0902 +class Line: + """Implement the line object and suspiciousness calculation.""" + + def __init__(self, file_path: str, line_num: int) -> None: + """Initialize a line object. + + Args: + file_path (str): Path to the file where the line exists + line_num (int): number of the line in the file + """ + self.path = file_path + self.number = line_num + self.passed_by: List[str] = [] + self.failed_by: List[str] = [] + self.skipped_by: List[str] = [] + self.sus_scores = { + TARAN: -1.0, + OCHIAI: -1.0, + DSTAR: -1.0, + OCHIAI2: -1.0, + } + self.tiebreakers = { + CYCLOMATIC: 0.0, + LOGICAL: 0.0, + ENHANCED: 0.0, + # *SHOULD ALWAYS STAY ZERO + RANDOM: 0.0, + } + + def sus(self, method: str, passed_total: int, failed_total: int, power=3): + """Calculate the suspiciousness score using the passed method. + + Args: + method (str): name of the method to use + """ + if method.lower() == TARAN: + self.sus_scores[TARAN] = Line.tarantula( + len(self.failed_by), + len(self.passed_by), + passed_total, + failed_total, + ) + elif method.lower() == OCHIAI: + self.sus_scores[OCHIAI] = Line.ochiai( + len(self.failed_by), len(self.passed_by), failed_total + ) + elif method.lower() == DSTAR: + self.sus_scores[DSTAR] = Line.dstar( + len(self.failed_by), len(self.passed_by), failed_total, power + ) + elif method.lower() == OCHIAI2: + self.sus_scores[OCHIAI2] = Line.ochiai2( + len(self.failed_by), + len(self.passed_by), + passed_total, + failed_total, + ) + else: + raise Exception("ERROR: unknown suspiciousness method") + + def sus_all(self, passed_total: int, failed_total: int, power=3): + """Calculate the suspiciousness score for all available methods.""" + self.sus(TARAN, passed_total, failed_total) + self.sus(OCHIAI, passed_total, failed_total) + self.sus(DSTAR, passed_total, failed_total, power=power) + self.sus(OCHIAI2, passed_total, failed_total) + + def as_dict(self): + """Return line information as json writable dictionary.""" + return self.__dict__ + + def as_csv(self): + """Return line information as csv writable list.""" + return [ + self.path, + self.number, + self.sus_scores[TARAN], + self.sus_scores[OCHIAI], + self.sus_scores[OCHIAI2], + self.sus_scores[DSTAR], + ] + + def sus_text(self, methods): + """Return a tuple of string of line information and score value.""" + sus_list = [] + for method_name in methods: + sus_list.append(self.sus_scores[method_name]) + return (self.path, self.number, sus_list) + + @staticmethod + def tarantula( + failed_cover: int, passed_cover: int, total_passed: int, total_failed: int + ) -> float: + """Calculate suspiciousness score using the tarantula approach. + + Args: + failed_cover (int): total number of failed test cases that cover the line + passed_cover (int): total number of passed test cases that cover the line + total_passed (int): total number of passed test cases + total_failed (int): total number of failed test cases + + Returns: + float: suspiciousness score using tarantula + """ + if total_passed == 0: + return 1 + if total_failed == 0: + return 0 + score = (failed_cover / total_failed) / ( + (passed_cover / total_passed) + (failed_cover / total_failed) + ) + return round(score, 4) + + @staticmethod + def ochiai(failed_cover: int, passed_cover: int, total_failed: int) -> float: + """Calculate suspiciousness score using the ochiai approach. + + Args: + failed_cover (int): total number of failed test cases that cover the line + passed_cover (int): total number of passed test cases that cover the line + total_failed (int): total number of failed test cases + + Returns: + float: suspiciousness score using ochiai + """ + if total_failed == 0 or failed_cover == 0: + return 0 + score = failed_cover / math.sqrt(total_failed * (passed_cover + failed_cover)) + return round(score, 4) + + @staticmethod + def dstar( + failed_cover: int, passed_cover: int, total_failed: int, power=3 + ) -> float: + """Calculate suspiciousness score using the dstar approach. + + Args: + failed_cover (int): total number of failed test cases that cover the line + passed_cover (int): total number of passed test cases that cover the line + total_failed (int): total number of failed test cases + power (int, optional): Power to use in the equation. Defaults to 3. + + Returns: + float: suspiciousness score using dstar + """ + uncovered_failed = total_failed - failed_cover + if passed_cover + uncovered_failed == 0: + return float("inf") + score = math.pow(failed_cover, power) / (passed_cover + uncovered_failed) + return round(score, 4) + + @staticmethod + def ochiai2( + failed_cover: int, passed_cover: int, total_passed: int, total_failed: int + ) -> float: + """Calculate suspiciousness score using the ochiai2 approach. + + Args: + failed_cover (int): total number of failed test cases that cover the line + passed_cover (int): total number of passed test cases that cover the line + total_passed (int): total number of passed test cases + total_failed (int): total number of failed test cases + + Returns: + float: suspiciousness score using ochiai2 + """ + # !DIVISION BY ZERO WHEN + # ?If there are no tests that cover the statement: not happening, we're + # only looking at covered statements to begin with + # !If there are no tests that do not cover the statement: UNSURE + # ?If the total failed is zero: not possible, for AFLuent to run, there + # has to be at least one failure + # ?If total passed is zero => everything is suspicious, no info really + passed_uncover = total_passed - passed_cover + failed_uncover = total_failed - failed_cover + total_cover = passed_cover + failed_cover + total_uncover = passed_uncover + failed_uncover + if total_passed == 0: + return 1.0 + if total_uncover == 0: + return 0 + if total_failed == 0: + return 0 + if total_cover == 0: + return 0 + numerator = failed_cover * passed_uncover + denominator = math.sqrt( + total_cover * total_uncover * total_failed * total_passed + ) + score = numerator / denominator + return round(score, 4) diff --git a/afluent/main.py b/afluent/main.py new file mode 100644 index 0000000000000000000000000000000000000000..1406bb22adfcb210070af980276ef17a6912687c --- /dev/null +++ b/afluent/main.py @@ -0,0 +1,243 @@ +"""Define Pytest Hooks that run AFLuent.""" + +import json + +from time import time +import coverage # type: ignore[import] +import pytest # type: ignore[import] +from console import bg, fg, fx # type: ignore[import] + +from afluent import spectrum_parser + + +WARNING = fx.bold + fg.white + bg.orange +ERROR = fx.bold + fg.white + bg.red +VALID = fx.bold + fg.white + bg.green + +CONFLICTING_PLUGINS = ["pytest_cov"] + + +def pytest_addoption(parser): + """Add AFLuent command line group and arguments to accept.""" + afluent_group = parser.getgroup("afluent", "Automated Fault Localization (AFLuent)") + afluent_group.addoption( + "--afl-debug", + "--afl", + dest="afl_enable", + action="store_true", + default=False, + help="Enable AFLuent", + ) + afluent_group.addoption( + "--tarantula", + dest="afl_methods", + action="append_const", + const="tarantula", + help="Enable fault localization using Tarantula", + ) + afluent_group.addoption( + "--ochiai", + dest="afl_methods", + action="append_const", + const="ochiai", + help="Enable fault localization using Ochiai", + ) + afluent_group.addoption( + "--ochiai2", + dest="afl_methods", + action="append_const", + const="ochiai2", + help="Enable fault localization using Ochiai2", + ) + afluent_group.addoption( + "--dstar", + dest="afl_methods", + action="append_const", + const="dstar", + help="Enable fault localization using Dstar", + ) + afluent_group.addoption( + "--dstar-pow", + dest="dstar_pow", + default=3, + action="store", + type=int, + help="Power to use when calculating Dstar score, default to 3", + ) + afluent_group.addoption( + "--afl-results", + dest="results_num", + default=20, + action="store", + type=int, + help="Number of results to display in the score report , default to 20", + ) + afluent_group.addoption( + "--afl-ignore", + dest="afl_ignore", + action="extend", + nargs="*", + type=str, + help="File patterns to ignore when calculating coverage for AFLuent (example: tests/*).", + ) + afluent_group.addoption( + "--report", + dest="report_type", + action="store", + default=None, + type=str, + choices=["json", "csv", "eval"], + help="Store report after AFLuent run.", + ) + afluent_group.addoption( + "--per-test-report", + dest="per_test", + action="store_true", + help="Get per test case coverage report.", + ) + afluent_group.addoption( + "--tiebreaker", + dest="tiebreaker", + action="store", + default="random", + type=str, + choices=["random", "cyclomatic", "logical", "enhanced"], + help="Type of tie breaking approach.", + ) + + +def pytest_cmdline_main(config): + """Check if AFLuent is enabled and register the plugin object.""" + # check if the argument to enable afluent exists and create the object with + # the passed configuration + for plugin in CONFLICTING_PLUGINS: + if config.pluginmanager.hasplugin(plugin): + print( + WARNING( + f"\n{plugin} plugin conflicts with AFLuent, consider disabling\n" + + "it for this session to get the most accurate fault localization results.\n\n" + ) + ) + + if config.getoption("afl_enable"): + # Check if exit after failure is enabled and display warning message + if config.getoption("--maxfail"): + print( + WARNING( + "\nExit after failure detected. AFLuent gives more " + + "accurate results if the full test suite was ran.\n\n" + + "Consider removing `-x` and/or `--maxfail` from CLI arguments." + ) + ) + print() + plugin = Afluent(config) + config.pluginmanager.register(plugin, "Afluent") + else: + print( + WARNING( + "\nAFLuent is disabled. Enable AFLuent by adding " + "--afl or --afl-debug to the test command." + ) + ) + print() + + +class Afluent: + """Contain all the functionalities and hooks of the AFLuent plugin.""" + + # pylint: disable=R0913, R0902 + def __init__(self, pytest_config): + """Initialize a plugin object with it's pytest hooks.""" + self.methods = pytest_config.getoption("afl_methods") + # if no methods were passed, include all of them + if not self.methods: + self.methods = ["dstar", "tarantula", "ochiai", "ochiai2"] + self.dstar_pow = pytest_config.getoption("dstar_pow") + self.results_num = pytest_config.getoption("results_num") + self.ignore = pytest_config.getoption("afl_ignore") + self.report = pytest_config.getoption("report_type") + self.per_test = pytest_config.getoption("per_test") + self.tiebreaker = pytest_config.getoption("tiebreaker") + if self.report == "eval": + self.eval_mode = True + else: + self.eval_mode = False + self.session_spectrum = {} + self.cov = coverage.Coverage( + data_file=None, + auto_data=False, + branch=True, + config_file=False, + omit=self.ignore, + ) + + @pytest.hookimpl(hookwrapper=True) + def pytest_pyfunc_call(self, pyfuncitem): + """Calculate the coverage of each test case and add it to spectrum.""" + try: + self.cov.start() + yield + self.cov.stop() + coverage_data = self.cov.get_data() + item_key = f"{pyfuncitem.parent.name}_{pyfuncitem.name}" + self.session_spectrum[item_key] = { + "coverage": {}, + "result": "notSet", + } + for measured_file in coverage_data.measured_files(): + self.session_spectrum[item_key]["coverage"][ + measured_file + ] = self.cov.get_data().lines(measured_file) + except coverage.exceptions.CoverageWarning: + pass + self.cov.erase() + + @pytest.hookimpl(hookwrapper=True) + def pytest_runtest_makereport(self, item): + """Store the outcome of the test case as passed, failed, or skipped.""" + outcome = yield + item_key = f"{item.parent.name}_{item.name}" + if outcome.get_result().when == "call" and item_key in self.session_spectrum: + self.session_spectrum[item_key]["result"] = outcome.get_result().outcome + + def pytest_sessionfinish(self, session, exitstatus): + """Perform the spectrum analysis if at least one test fails.""" + test_end_time = time() + reporter = session.config.pluginmanager.get_plugin("terminalreporter") + # pylint: disable=W0212 + test_time = round(test_end_time - reporter._sessionstarttime, 6) + localization_time = 0 + # Store generated json + if self.per_test: + with open( + "afluent_per_test_report.json", "w+", encoding="utf-8" + ) as outfile: + json.dump(self.session_spectrum, outfile, indent=4) + # Tests passed, exit status is 0 + if exitstatus == 0: + exit_message = VALID( + "\n\nAll tests passed, no need to diagnose using AFLuent." + ) + print(f"{exit_message}") + # some tests failed exit status + elif exitstatus == 1: + exit_message = ERROR( + "\n\nFailing tests detected. Diagnosing using AFLuent..." + ) + print(f"{exit_message}") + start_time = time() + full_spectrum = spectrum_parser.Spectrum( + self.session_spectrum, + dstar_pow=self.dstar_pow, + tiebreaker=self.tiebreaker, + eval_mode=self.eval_mode, + ) + end_time = time() + localization_time = round(end_time - start_time, 6) + full_spectrum.print_report(self.methods, self.results_num) + if self.report: + print(f"Storing {self.report} report...") + full_spectrum.store_report(self.report) + timings = {"test_time": test_time, "localization_time": localization_time} + with open("afluent_timings.json", "w+", encoding="utf-8") as outfile: + json.dump(timings, outfile, indent=4) diff --git a/afluent/proj_file.py b/afluent/proj_file.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc1b3669d0e7b6e01bca2cbb6e40095cc69d519 --- /dev/null +++ b/afluent/proj_file.py @@ -0,0 +1,89 @@ +"""Create object oriented structure for files carrying line coverage information.""" +from typing import Dict + +from afluent import tiebreak_generator + +from afluent import line + + +class ProjFile: + """Store coverage information about python files under test.""" + + def __init__(self, name: str) -> None: + """Initialize a ProjFile object. + + Args: + name (str): path of the file under test + """ + self.name = name + self.lines: Dict[int, line.Line] = {} + self.cyclomatic_complexity_data: Dict[int, int] = {} + self.logical_tiebreak_data: Dict[int, int] = {} + self.enhanced_tiebreak_data: Dict[int, float] = {} + + def update_file( + self, covered_lines: list[int], test_result: str, test_case_name: str + ): + """Update lines information in a file object. + + Args: + covered_lines (list[int]): list of integer values of the lines covered + test_result (str): one of three possible values `passed` `failed` or `skipped` + test_case_name (str): name of the test case being ran + + Raises: + Exception: when a result is not one of the three possible values + """ + for line_number in covered_lines: + # Line doesn't exist in the dataset, create new one + if line_number not in self.lines: + line_obj = line.Line(self.name, line_number) + if self.cyclomatic_complexity_data: + # get the complexity of the line + line_obj.tiebreakers[ + "cyclomatic" + ] = self.cyclomatic_complexity_data[line_number] + if self.logical_tiebreak_data: + line_obj.tiebreakers["logical"] = self.logical_tiebreak_data[ + line_number + ] + if self.enhanced_tiebreak_data: + line_obj.tiebreakers["enhanced"] = self.enhanced_tiebreak_data[ + line_number + ] + + self.lines[line_number] = line_obj + if test_result == "passed": + self.lines[line_number].passed_by.append(test_case_name) + elif test_result == "failed": + self.lines[line_number].failed_by.append(test_case_name) + elif test_result == "skipped": + self.lines[line_number].skipped_by.append(test_case_name) + else: + raise Exception(f"Unknown test result for {test_case_name}") + + def get_cyclomatic_tiebreaker_dataset(self): + """Use the file path to calculate cyclomatic complexity and update the data.""" + # set cyclomatic complexity to be enabled + cc_generator = tiebreak_generator.CyclomaticComplexityGenerator(self.name) + cc_generator.calculate_syntax_complexity() + self.cyclomatic_complexity_data = cc_generator.data + + def get_logical_tiebreaker_dataset(self): + """Use tiebreak generator to get the logical tiebreaker dataset.""" + mutant_density_generator = tiebreak_generator.LogicalTieBreaker(self.name) + mutant_density_generator.calculate_mutant_density() + self.logical_tiebreak_data = mutant_density_generator.score + + def get_enhanced_tiebreaker_dataset(self): + """Use tiebreak generator to get the enhanced tiebreaker dataset.""" + generator = tiebreak_generator.EnhancedTieBreaker(self.name) + generator.calculate_mutant_density() + self.enhanced_tiebreak_data = generator.score + + def as_dict(self): + """Return lines as a json writable dictionary.""" + data_dictionary = {} + for line_num, line_obj in self.lines.items(): + data_dictionary[str(line_num)] = line_obj.as_dict() + return data_dictionary diff --git a/afluent/spectrum_parser.py b/afluent/spectrum_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..6688d20e40de8375639bad05558510ab5643a8ef --- /dev/null +++ b/afluent/spectrum_parser.py @@ -0,0 +1,255 @@ +"""Implement parsing and reassembling functions for coverage data.""" + +import csv +import json +import random + +from typing import Any, Dict, List, Tuple + +from console import fg, bg, fx # type: ignore[import] +from tabulate import tabulate +from afluent import proj_file, line + + +METHOD_NAMES = ["tarantula", "ochiai", "ochiai2", "dstar"] +TIEBREAKERS = ["random", "cyclomatic", "logical", "enhanced"] + +PALETTE = { + "severe": fg.white + fx.bold + bg.lightred, + "risky": fg.white + fx.bold + bg.i208, + "mild": fg.white + fx.bold + bg.yellow, + "safe": fg.white + fx.bold + bg.green, + "location_line": fg.white, +} + + +class Spectrum: + """Store all the information for individual files and lines coverage.""" + + def __init__( + self, config, dstar_pow=3, tiebreaker="random", eval_mode=False + ) -> None: + """Initialize a spectrum object. + + Args: + config (dict): per-test coverage information + dstar_pow (int): power to use when calculating scores using dstar + """ + self.config = config + self.reassembled_data: Dict[str, proj_file.ProjFile] = {} + self.sorted_lines: List[line.Line] = [] + self.totals = {"passed": 0, "failed": 0, "skipped": 0} + self.dstar_pow = dstar_pow + self.tiebreaker = tiebreaker + self.eval_mode = eval_mode + self.reassemble() + self.calculate_sus() + + def generate_report( + self, methods: List[str], max_items=-1 + ) -> List[Tuple[Any, ...]]: + """Generate a list of tuples containing report information.""" + report_list = [] + # Gather up all the line objects in one list + all_lines: List[line.Line] = [] + for file_obj in self.reassembled_data.values(): + all_lines.extend(file_obj.lines.values()) + # Sort the lines based on the first method name used in the list + sorted_lines = Spectrum.generate_rankings( + all_lines, methods[0], tiebreaker=self.tiebreaker + ) + # store as an instance variable to generate reports later + self.sorted_lines = sorted_lines + if max_items > 0: + sorted_lines = sorted_lines[:max_items] + # pylint: disable=C0200 + for line_index in range(0, len(sorted_lines)): + line_obj = sorted_lines[line_index] + line_path, line_number, sus_scores = line_obj.sus_text(methods) + line_path = f"{PALETTE['location_line'](line_path)}" + line_number = f"{PALETTE['location_line'](str(line_number))}" + current_row = [line_path, line_number] + format_function = Spectrum.calculate_severity( + methods[0], sus_scores[0], line_index, len(sorted_lines) + ) + for method_score in sus_scores: + current_row.append(f"{format_function(str(method_score))}") + report_list.append(tuple(current_row)) + return report_list + + def reassemble(self): + """Reassemble the coverage information on a file and line basis.""" + # Config is empty, return nothing + if not self.config: + return + # iterate through every test case in the spectrum report + for test_case_name, spectrum_dict in self.config.items(): + test_result = spectrum_dict["result"] + # increment the totals + self.totals[test_result] += 1 + for file_name, lines_covered in spectrum_dict["coverage"].items(): + if file_name not in self.reassembled_data: + # Initialize a new object of one doesn't already exist + file_obj = proj_file.ProjFile(file_name) + if self.eval_mode: + # populate all tieberaker datasets + file_obj.get_logical_tiebreaker_dataset() + file_obj.get_enhanced_tiebreaker_dataset() + file_obj.get_cyclomatic_tiebreaker_dataset() + elif self.tiebreaker == "logical": + # collect logical tiebreak dataset only + file_obj.get_logical_tiebreaker_dataset() + elif self.tiebreaker == "enhanced": + # collect enhanced tiebreak dataset only + file_obj.get_enhanced_tiebreaker_dataset() + elif self.tiebreaker == "cyclomatic": + # collect cyclometer dataset only + file_obj.get_cyclomatic_tiebreaker_dataset() + # * Random tiebreaker doesn't need dataset + self.reassembled_data[file_name] = file_obj + self.reassembled_data[file_name].update_file( + lines_covered, test_result, test_case_name + ) + + def calculate_sus(self): + """Iterate through reassembeled data and calculate the suspiciousness of every line.""" + for _, current_file in self.reassembled_data.items(): + for _, current_line in current_file.lines.items(): + current_line.sus_all( + self.totals["passed"], self.totals["failed"], power=self.dstar_pow + ) + + def as_dict(self): + """Return the spectrum information as a JSON writable dictionary.""" + data_dict = {} + for file_name, file_obj in self.reassembled_data.items(): + data_dict[file_name] = file_obj.as_dict() + + return data_dict + + def print_report(self, methods: List[str], items_num: int): + """Print a nicely formatted suspiciousness report using the chosen method.""" + for method_name in methods: + if method_name not in METHOD_NAMES: + raise Exception(f"ERROR: Invalid method name {method_name}") + print() + header_text = "============================ AFLuent Report ===============================" + table_headers = [ + PALETTE["location_line"]("File Path"), + PALETTE["location_line"]("Line Number"), + ] + for method_name in methods: + table_headers.append(PALETTE["location_line"](f"{method_name} Score")) + print(f"{PALETTE['location_line'](header_text)}") + print( + tabulate( + self.generate_report(methods, max_items=items_num), + headers=table_headers, + tablefmt="rst", + ) + ) + + def store_report(self, report_type): + """Create and store a report file.""" + if report_type == "json": + data_dict = {} + lines_list = list(map(lambda x: x.as_dict(), self.sorted_lines)) + data_dict["ranking"] = lines_list + with open("afluent_report.json", "w+", encoding="utf-8") as outfile: + json.dump(data_dict, outfile, indent=4) + elif report_type == "csv": + header = [ + "Path", + "Line number", + "Tarantula Score", + "Ochiai Score", + "Ochiai2 Score", + "Dstar Score", + ] + with open("afluent_report.csv", "w+", encoding="utf-8") as outfile: + csv_writer = csv.writer(outfile) + csv_writer.writerow(header) + lines_list = list(map(lambda x: x.as_csv(), self.sorted_lines)) + csv_writer.writerows(lines_list) + + elif report_type == "eval": + self.produce_full_eval_report() + else: + raise Exception(f"Error:Unknown report type {report_type}.") + + # pylint: disable=W0640 + def produce_full_eval_report(self): + """Produce csv reports for all equation tie breaker combinatoins.""" + for method in METHOD_NAMES: + for tiebreaker in TIEBREAKERS: + ranked_lines = Spectrum.generate_rankings( + self.sorted_lines, method, tiebreaker=tiebreaker + ) + file_to_store = f"{method}_{tiebreaker}_report.csv" + header = [ + "Path", + "Line number", + f"{method} score", + f"{tiebreaker} score", + ] + with open(file_to_store, "w+", encoding="utf-8") as outfile: + csv_writer = csv.writer(outfile) + csv_writer.writerow(header) + lines_list = list( + map( + lambda x: [ + x.path, + x.number, + x.sus_scores[method], + x.tiebreakers[tiebreaker], + ], + ranked_lines, + ) + ) + csv_writer.writerows(lines_list) + + @staticmethod + def generate_rankings( + all_lines: List[line.Line], method: str, tiebreaker="random" + ) -> List[line.Line]: + """Return a list of line objects ranked from the most to least suspicious. + + Args: + method (str): name of the suspiciousness score to use for sorting + """ + # If random, just sort by the sus scores + if tiebreaker == "random": + # Introduce some randomness before sorting + random.shuffle(all_lines) + all_lines.sort( + key=lambda x: x.sus_scores[method], + reverse=True, + ) + # Otherwise, use the tiebreaker scores + else: + all_lines.sort( + key=lambda x: (x.sus_scores[method], x.tiebreakers[tiebreaker]), + reverse=True, + ) + # store the sorted list as an attribute + return all_lines + + @staticmethod + def calculate_severity(method: str, sus_score: float, rank: int, out_of: int): + """Return a function to format strings according to score severity. + + Args: + method (str): name of the suspiciousness method used + sus_score (float): suspiciousness score of the line + rank (int): the rank of this line in the sorted list + out_of (int): length of the sorted list + """ + if sus_score <= 0: + return PALETTE["safe"] + if (method in ["tarantula", "ochiai", "ochiai2"]) and sus_score == 1: + return PALETTE["severe"] + if method == "dstar" and sus_score == float("inf"): + return PALETTE["severe"] + if rank / out_of <= 0.2: + return PALETTE["risky"] + return PALETTE["mild"] diff --git a/afluent/tiebreak_generator.py b/afluent/tiebreak_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..4c58519841c4cedc1590f778923d1f7907051498 --- /dev/null +++ b/afluent/tiebreak_generator.py @@ -0,0 +1,367 @@ +"""Define complexity generators and criteria to calculate complexity.""" + +from typing import Any, Dict, List +import libcst as cst +from libcst import metadata +from libcst import matchers +import radon # type: ignore[import] +import radon.complexity as cc # type: ignore[import] + +MUTANTS = [ + matchers.BitInvert, + matchers.Not, + matchers.Minus, + matchers.Plus, + matchers.And, + matchers.Or, + matchers.Add, + matchers.BitAnd, + matchers.BitOr, + matchers.BitXor, + matchers.Divide, + matchers.FloorDivide, + matchers.LeftShift, + matchers.MatrixMultiply, + matchers.Modulo, + matchers.Multiply, + matchers.Power, + matchers.RightShift, + matchers.Subtract, + matchers.Equal, + matchers.GreaterThan, + matchers.GreaterThanEqual, + matchers.In, + matchers.Is, + matchers.LessThan, + matchers.LessThanEqual, + matchers.NotEqual, + matchers.IsNot, + matchers.NotIn, + matchers.AddAssign, + matchers.BitAndAssign, + matchers.BitOrAssign, + matchers.BitXorAssign, + matchers.DivideAssign, + matchers.FloorDivideAssign, + matchers.LeftShiftAssign, + matchers.MatrixMultiplyAssign, + matchers.ModuloAssign, + matchers.MultiplyAssign, + matchers.PowerAssign, + matchers.RightShiftAssign, + matchers.SubtractAssign, +] + +ENHANCED_MUTANTS = [ + matchers.AnnAssign, + matchers.Assign, + matchers.Call, + matchers.Subscript, + matchers.Tuple, + matchers.List, + matchers.SimpleString, + matchers.Dict, + matchers.Integer, + matchers.Float, +] + MUTANTS + + +class FullVisitor(cst.CSTVisitor): + """Locate specific nodes and organize by line number and calculate their complexity.""" + + METADATA_DEPENDENCIES = (metadata.PositionProvider,) + + def __init__(self, filler_dict: dict) -> None: + """Initialize the class as a visitor. + + Args: + filler_dict (dict): empty dictionary containing all line numbers of + a file. + """ + super().__init__() + self.mutants_by_location = filler_dict + self.score: Dict[int, float] = {} + + def visit_If(self, node: cst.If) -> None: + """Store the metadata of if statements when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def visit_FunctionDef(self, node: cst.FunctionDef) -> None: + """Store the metadata of function definition when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None: + """Store the metadata of general statements when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def visit_While(self, node: cst.While) -> None: + """Store the metadata of while loops when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def visit_For(self, node: cst.For) -> None: + """Store the metadata of for loops when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def visit_With(self, node: cst.With) -> None: + """Store the metadata of with statements when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def get_node_metadata_dict(self, node): + """Organize the metadata dictionary.""" + node_type = type(node).__name__ + metadata_dict = { + "start": self.get_metadata(metadata.PositionProvider, node).start.line, + "end": self.get_metadata(metadata.PositionProvider, node).end.line, + "type": node_type, + "complexity": COMPLEXITY_FUNC[node_type](node), + } + return metadata_dict + + def fill_locations_range(self, node_metadata): + """Distribute the metadata for all nodes in the same block.""" + start = node_metadata["start"] + end = node_metadata["end"] + for line_num in range(start, end + 1): + if line_num in self.mutants_by_location: + self.mutants_by_location[line_num].append(node_metadata) + + def calculate_score(self): + """Iterate through the collected data and generate a score for each line.""" + for key, value in self.mutants_by_location.items(): + self.score[key] = FullVisitor.get_average_score(value) + + @staticmethod + def get_average_score(items_list: List[Dict[str, Any]]) -> float: + """Calculate the average score for a single line. + + Args: + items_list (List[Dict[str, Any]]): List of nodes with their + information + + Returns: + float: score for the line + """ + statement_sum = 0 + statement_num = 0 + other_sum = 0 + other_num = 0 + # iterate through the list in a reverse order + for item in items_list[::-1]: + if item["type"] == "SimpleStatementLine": + statement_sum += item["complexity"] + statement_num += 1 + else: + other_sum += item["complexity"] + other_num += 1 + # avoid division by zero + if statement_num == 0: + statement_num += 1 + if other_num == 0: + other_num += 1 + score = ((statement_sum / statement_num) + (other_sum / other_num)) / 2 + return round(score, 5) + + @staticmethod + def count_mutants(node, mutant_set): + """Count the number of possible mutants in a node using the MUTANTS variable.""" + total = 0 + for mutant in mutant_set: + total += len(matchers.findall(node, mutant())) + return total + + @staticmethod + def get_funcdef_complexity(node): + """Calculate the complexity of a function definition.""" + return len(node.params.params) + + @staticmethod + def get_if_complexity(node): + """Calculate the complexity of an if statement.""" + # complexity of if statement= number of mutants in the test condition + if node.test: + total = FullVisitor.count_mutants(node.test, ENHANCED_MUTANTS) + return total + return 0 + + @staticmethod + def get_statement_complexity(node): + """Calculate the complexity of a general statement.""" + # Complexity of a statement = number of mutants + total = FullVisitor.count_mutants(node, ENHANCED_MUTANTS) + return total + + @staticmethod + def get_while_complexity(node): + """Calculate the complexity of a while loop.""" + if node.test: + total = FullVisitor.count_mutants(node.test, ENHANCED_MUTANTS) + return total + return 0 + + @staticmethod + def get_for_complexity(node): + """Calculate the complexity of a for loop.""" + target_mutants = 0 + iterable_mutants = 0 + if node.target: + target_mutants = FullVisitor.count_mutants(node.target, ENHANCED_MUTANTS) + if node.iter: + iterable_mutants = FullVisitor.count_mutants(node.iter, ENHANCED_MUTANTS) + return target_mutants + iterable_mutants + + @staticmethod + def get_with_complexity(node): + """Calculate the complexity of a with statement.""" + total = 0 + if node.items: + for with_item in node.items: + total += FullVisitor.count_mutants(with_item, ENHANCED_MUTANTS) + return 0 + + +COMPLEXITY_FUNC = { + "FunctionDef": FullVisitor.get_funcdef_complexity, + "If": FullVisitor.get_if_complexity, + "SimpleStatementLine": FullVisitor.get_statement_complexity, + "While": FullVisitor.get_while_complexity, + "For": FullVisitor.get_for_complexity, + "With": FullVisitor.get_with_complexity, +} + + +class StatementVisitor(cst.CSTVisitor): + """Locate specific nodes and organize by line number and calculate their complexity.""" + + METADATA_DEPENDENCIES = (metadata.PositionProvider,) + + def __init__(self, filler_dict: dict) -> None: + """Initialize the class as a visitor. + + Args: + filler_dict (dict): empty dictionary containing all line numbers of + a file. + """ + super().__init__() + self.mutants_by_location = filler_dict + + def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None: + """Store the metadata of general statements when visited.""" + node_metadata = self.get_node_metadata_dict(node) + self.fill_locations_range(node_metadata) + + def get_node_metadata_dict(self, node): + """Organize the metadata dictionary.""" + node_type = type(node).__name__ + metadata_dict = { + "start": self.get_metadata(metadata.PositionProvider, node).start.line, + "end": self.get_metadata(metadata.PositionProvider, node).end.line, + "type": node_type, + } + if node_type == "SimpleStatementLine": + metadata_dict["complexity"] = StatementVisitor.get_statement_complexity( + node + ) + return metadata_dict + + def fill_locations_range(self, node_metadata): + """Distribute the metadata for all nodes in the same block.""" + start = node_metadata["start"] + end = node_metadata["end"] + for line_num in range(start, end + 1): + if line_num in self.mutants_by_location: + self.mutants_by_location[line_num] = node_metadata["complexity"] + + @staticmethod + def get_statement_complexity(node): + """Calculate the complexity of a general statement.""" + # Complexity of a statement = number of mutants + total = StatementVisitor.count_mutants(node) + return total + + @staticmethod + def count_mutants(node): + """Count the number of possible mutants in a node using the MUTANTS variable.""" + total = 0 + for mutant in MUTANTS: + total += len(matchers.findall(node, mutant())) + return total + + +# pylint: disable=R0903 +class EnhancedTieBreaker: + """Store the full syntax mutant density data set and call the finder.""" + + def __init__(self, file_path: str) -> None: + """Initialize the generator.""" + self.path = file_path + self.data: Dict[int, List[Dict[str, Any]]] = {} + self.score: Dict[int, float] = {} + + def calculate_mutant_density(self): + """Get the full file mutant density dataset.""" + with open(self.path, "r", encoding="utf-8") as infile: + file_text = infile.read() + module_obj = cst.parse_module(file_text) + lines_num = len(file_text.splitlines()) + filler_dict = {i: [] for i in range(1, lines_num + 1)} + wrapper = metadata.MetadataWrapper(module_obj) + finder = FullVisitor(filler_dict) + wrapper.visit(finder) + self.data = finder.mutants_by_location + finder.calculate_score() + self.score = finder.score + + +# pylint: disable=R0903 +class LogicalTieBreaker: + """Store the full syntax mutant density data set and call the finder.""" + + def __init__(self, file_path: str) -> None: + """Initialize the generator.""" + self.path = file_path + self.score: Dict[int, int] = {} + + def calculate_mutant_density(self): + """Get the full file mutant density dataset.""" + with open(self.path, "r", encoding="utf-8") as infile: + file_text = infile.read() + module_obj = cst.parse_module(file_text) + lines_num = len(file_text.splitlines()) + filler_dict = {i: 0 for i in range(1, lines_num + 1)} + wrapper = metadata.MetadataWrapper(module_obj) + finder = StatementVisitor(filler_dict) + wrapper.visit(finder) + self.score = finder.mutants_by_location + + +# pylint: disable=R0903 +class CyclomaticComplexityGenerator: + """Store the dataset for cyclomatic complexity in the file.""" + + def __init__(self, file_path) -> None: + """Initialize the generator.""" + self.path = file_path + self.data: Dict[int, int] = {} + + def calculate_syntax_complexity(self): + """Get the full dataset for cyclomatic complexity.""" + with open(self.path, "r", encoding="utf-8") as infile: + file_string = infile.read() + lines_num = len(file_string.splitlines()) + complexity_data = cc.sorted_results(cc.cc_visit(file_string), cc.LINES) + filler_dict = {i: 0 for i in range(1, lines_num + 1)} + # reassemble complexity data to follow this format + # List(Tuple(line_start:int, line_end:int, complexity_score:int)) + for item in complexity_data: + # Check if the current item is a Function and add it's information + if isinstance(item, radon.visitors.Function): + # fill the filler_dict with the complexity score + for number in range(item.lineno, item.endline + 1): + filler_dict[number] = item.complexity + self.data = filler_dict diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46f591b1d87bf0d23e0167657929425dd693f949 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Standard init file.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..2f83b68ba33e86d3233e22f4c2cc0e3ce0108e0a --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,25 @@ +"""Implement fixtures and hooks for pytest session.""" + +import json +import pathlib +import pytest + +# pylint: disable=C0103,W0602 +full_test_data = {} + + +@pytest.hookimpl() +def pytest_sessionstart(): + """Read and collect test data as part of the global test data dictionary.""" + test_data_files = pathlib.Path("./tests/test_data").glob("*.json") + for json_data_file in test_data_files: + with open(json_data_file, "r", encoding="utf-8") as data_file: + current_test_data = json.load(data_file) + global full_test_data + full_test_data[json_data_file.stem] = current_test_data + + +@pytest.fixture +def test_data(): + """Return full_test_data.""" + return full_test_data diff --git a/tests/test_data/__init__.py b/tests/test_data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46f591b1d87bf0d23e0167657929425dd693f949 --- /dev/null +++ b/tests/test_data/__init__.py @@ -0,0 +1 @@ +"""Standard init file.""" diff --git a/tests/test_data/sample_file.py b/tests/test_data/sample_file.py new file mode 100644 index 0000000000000000000000000000000000000000..54f0724f2fdb862018881cc6ef0121b9f6a5bdfe --- /dev/null +++ b/tests/test_data/sample_file.py @@ -0,0 +1,23 @@ +"""Use module is used for testing purposes only, do not modify.""" +# pylint: disable=C0116, E0602, W0612 + + +def some_function(arg1, arg2, arg3, arg4): # noqa + print("hello world!") + int1 = arg1 * arg3 / 5 - arg4 + int2 = arg4 ** arg3 + my_list = [1, 2, 3.6, 4, 5.4, "some string"] + my_dictionary = { + "first": arg1, + "second": arg2, + "third": arg3, + "fourth": arg4, + } + my_tuple = ("hello", "world") + result = some_other_function(arg2).process_somehow() + if not arg3 > arg2 and arg1 < arg4: + return arg2 >> 5 + while my_list[4] > my_dictionary["first"]: + my_variable = 54 + my_variable += arg1 / arg4 + return my_dictionary["first"] + "something here" diff --git a/tests/test_data/test_spectrum_init.json b/tests/test_data/test_spectrum_init.json new file mode 100644 index 0000000000000000000000000000000000000000..4eef5be85f3a01cb23f99a5df36732c61895b4e7 --- /dev/null +++ b/tests/test_data/test_spectrum_init.json @@ -0,0 +1,34 @@ +{ + "input_config": { + "test1": { + "coverage": { + "file1.py": [1, 2, 3, 4], + "file2.py": [1, 2, 3, 4, 5, 6] + }, + "result": "passed" + }, + "test2": { + "coverage": { + "file1.py": [3, 4, 5, 6], + "file2.py": [1, 2, 3, 6, 7, 8, 9] + }, + "result": "passed" + }, + "test3": { + "coverage": { + "file1.py": [5, 6, 7], + "file2.py": [9, 3, 5] + }, + "result": "failed" + }, + "test4": { + "coverage": {}, + "result": "skipped" + } + }, + "output_reassembled": { + "passed": 2, + "failed": 1, + "skipped": 1 + } +} \ No newline at end of file diff --git a/tests/test_line.py b/tests/test_line.py new file mode 100644 index 0000000000000000000000000000000000000000..c7e3ae0038ee8a7b27e74e0ede6cbb9199d92e1a --- /dev/null +++ b/tests/test_line.py @@ -0,0 +1,148 @@ +"""Test the line module and Line class.""" + +import pytest + +from afluent import line + + +def test_globals(): + """Check that global constants are of specific values.""" + assert line.TARAN == "tarantula" + assert line.OCHIAI == "ochiai" + assert line.OCHIAI2 == "ochiai2" + assert line.DSTAR == "dstar" + assert line.RANDOM == "random" + assert line.CYCLOMATIC == "cyclomatic" + assert line.LOGICAL == "logical" + assert line.ENHANCED == "enhanced" + + +@pytest.mark.parametrize( + "failed_cover,passed_cover,total_passed,total_failed,expected_score", + [ + (1, 0, 1, 1, 1), + (0, 1, 1, 1, 0), + (3, 1, 6, 4, 0.8182), + (0, 3, 5, 0, 0), + (4, 0, 0, 9, 1), + ], +) +def test_tarantula( + failed_cover, passed_cover, total_passed, total_failed, expected_score +): + """Check that the tarantula formula is correct.""" + assert ( + line.Line.tarantula(failed_cover, passed_cover, total_passed, total_failed) + == expected_score + ) + + +@pytest.mark.parametrize( + "failed_cover,passed_cover,total_failed,expected_score", + [ + (1, 0, 1, 1), + (3, 2, 6, 0.5477), + (0, 1, 6, 0), + ], +) +def test_ohiai(failed_cover, passed_cover, total_failed, expected_score): + """Check that the ohiai formula is correct.""" + assert line.Line.ochiai(failed_cover, passed_cover, total_failed) == expected_score + + +@pytest.mark.parametrize( + "failed_cover,passed_cover,total_failed,power,expected_score", + [ + (1, 0, 2, 3, 1), + (3, 2, 6, 3, 5.4), + (0, 1, 6, 3, 0), + (6, 0, 6, 3, float("inf")), + ], +) +def test_dstar(failed_cover, passed_cover, total_failed, power, expected_score): + """Check that the test_dstar formula is correct.""" + assert ( + line.Line.dstar(failed_cover, passed_cover, total_failed, power=power) + == expected_score + ) + + +@pytest.mark.parametrize( + "failed_cover,passed_cover,total_passed,total_failed,expected_score", + [ + (3, 0, 0, 6, 1), + (0, 0, 7, 0, 0), + (3, 3, 3, 3, 0), + (0, 0, 5, 5, 0), + (3, 2, 7, 6, 0.366), + ], +) +def test_ochiai2( + failed_cover, passed_cover, total_passed, total_failed, expected_score +): + """Check that the ochiai2 formula is correct.""" + assert ( + line.Line.ochiai2(failed_cover, passed_cover, total_passed, total_failed) + == expected_score + ) + + +def test_line_create(): + """Check that line object can be instantiated correctly.""" + test_line = line.Line("sample/path/to/file.py", 14) + assert test_line.path == "sample/path/to/file.py" + assert test_line.number == 14 + assert not (test_line.passed_by or test_line.failed_by or test_line.skipped_by) + assert list(test_line.sus_scores.values()) == [-1.0, -1.0, -1.0, -1.0] + assert list(test_line.tiebreakers.values()) == [0, 0, 0, 0] + + +def test_line_sus_all(): + """Check that all suspiciousness scores can be calculated.""" + test_line = line.Line("sample/path/to/file.py", 14) + test_line.passed_by = ["test1", "test2"] + test_line.failed_by = ["test3", "test4", "test5"] + for sus_value in test_line.sus_scores.values(): + assert sus_value == -1.0 + test_line.sus_all(4, 6) + assert test_line.sus_scores["tarantula"] == 0.5 + assert test_line.sus_scores["ochiai"] == 0.5477 + assert test_line.sus_scores["dstar"] == 5.4 + + +def test_line_sus_unknown(): + """Check that an error is thrown when an unknown method is passed.""" + test_line = line.Line("sample/path/to/file.py", 14) + test_line.passed_by = ["test1", "test2"] + test_line.failed_by = ["test3", "test4", "test5"] + with pytest.raises(Exception): + test_line.sus("random", 5, 5) + + +def test_as_csv(): + """Check that a line is correctly converted to csv format.""" + test_line = line.Line("sample/path/to/file.py", 14) + assert test_line.as_csv() == ["sample/path/to/file.py", 14, -1, -1, -1, -1] + + +def test_sus_text(): + """Check that the correct tuple is returned.""" + test_line = line.Line("sample/path/to/file.py", 14) + test_line.sus_scores = { + "tarantula": 1.0, + "ochiai": 1.0, + "dstar": 15.0, + } + assert test_line.sus_text(["tarantula"]) == ("sample/path/to/file.py", 14, [1.0]) + assert test_line.sus_text(["ochiai"]) == ("sample/path/to/file.py", 14, [1.0]) + assert test_line.sus_text(["dstar"]) == ("sample/path/to/file.py", 14, [15.0]) + assert test_line.sus_text(["dstar", "tarantula"]) == ( + "sample/path/to/file.py", + 14, + [15.0, 1.0], + ) + + +# def test_something(): +# """Purposefully fail to check report.""" +# assert False diff --git a/tests/test_proj_file.py b/tests/test_proj_file.py new file mode 100644 index 0000000000000000000000000000000000000000..4607c22ac11617c300a0aa0d60025c01899754d2 --- /dev/null +++ b/tests/test_proj_file.py @@ -0,0 +1,139 @@ +"""Test the proj_file module and ProjFile class.""" + +import pytest +from afluent import line, proj_file + + +def test_projfile_init(): + """Test that a projFile object can be created.""" + test_projfile = proj_file.ProjFile("samplename.py") + assert test_projfile.name == "samplename.py" + assert not test_projfile.lines + + +def test_update_file_new_key(): + """Check that a line is created and updated in a new file.""" + test_projfile = proj_file.ProjFile("samplename.py") + covered_lines = [3, 6, 7, 9, 13] + test_projfile.update_file(covered_lines, "passed", "sample_testcase") + for line_num in covered_lines: + assert line_num in test_projfile.lines + assert isinstance(test_projfile.lines[line_num], line.Line) + assert test_projfile.lines[line_num].passed_by == ["sample_testcase"] + + +def test_update_file_existing_key_passed(): + """Check that a line is created and updated in a new file.""" + test_projfile = proj_file.ProjFile("samplename.py") + test_projfile.lines[5] = line.Line("samplename.py", 5) + test_projfile.lines[5].passed_by = [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + ] + covered_lines = [5, 6] + test_projfile.update_file(covered_lines, "passed", "sample_testcase") + assert test_projfile.lines[5].passed_by == [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + "sample_testcase", + ] + + +def test_update_file_existing_key_failed(): + """Check that a line is created and updated in a new file.""" + test_projfile = proj_file.ProjFile("samplename.py") + test_projfile.lines[5] = line.Line("samplename.py", 5) + test_projfile.lines[5].failed_by = [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + ] + covered_lines = [5, 6] + test_projfile.update_file(covered_lines, "failed", "sample_testcase") + assert test_projfile.lines[5].failed_by == [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + "sample_testcase", + ] + + +def test_update_file_existing_key_skipped(): + """Check that a line is created and updated in a new file.""" + test_projfile = proj_file.ProjFile("samplename.py") + test_projfile.lines[5] = line.Line("samplename.py", 5) + test_projfile.lines[5].skipped_by = [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + ] + covered_lines = [5, 6] + test_projfile.update_file(covered_lines, "skipped", "sample_testcase") + assert test_projfile.lines[5].skipped_by == [ + "sample_testcase2", + "sample_testcase3", + "sample_testcase4", + "sample_testcase", + ] + + +def test_update_file_unknown_result(): + """Check that a line is created and updated in a new file.""" + test_projfile = proj_file.ProjFile("samplename.py") + covered_lines = [5, 6] + with pytest.raises(Exception): + test_projfile.update_file(covered_lines, "random", "sample_testcase") + + +def test_get_datasets(): + """Check that all tiebreaker datasets can be populated. Regardless of accuracy.""" + test_projfile = proj_file.ProjFile("./tests/test_data/sample_file.py") + assert not test_projfile.cyclomatic_complexity_data + assert not test_projfile.logical_tiebreak_data + assert not test_projfile.enhanced_tiebreak_data + test_projfile.get_cyclomatic_tiebreaker_dataset() + test_projfile.get_logical_tiebreaker_dataset() + test_projfile.get_enhanced_tiebreaker_dataset() + assert test_projfile.cyclomatic_complexity_data + assert test_projfile.logical_tiebreak_data + assert test_projfile.enhanced_tiebreak_data + covered_lines = [6, 7, 8, 10] + test_projfile.update_file(covered_lines, "failed", "sample_testcase") + assert test_projfile.lines[6].tiebreakers == { + "cyclomatic": 4, + "logical": 0.0, + "enhanced": 3.0, + "random": 0, + } + assert test_projfile.lines[7].tiebreakers == { + "cyclomatic": 4, + "logical": 3, + "enhanced": 4.5, + "random": 0.0, + } + assert test_projfile.lines[8].tiebreakers == { + "cyclomatic": 4, + "logical": 1, + "enhanced": 3.0, + "random": 0.0, + } + assert test_projfile.lines[10].tiebreakers == { + "cyclomatic": 4, + "logical": 0.0, + "enhanced": 5, + "random": 0.0, + } + + +# def test_projfile_as_dict(): +# """Check that as_dict() return a correct dictionary.""" +# file_name = "samplename.py" +# test_projfile = proj_file.ProjFile(file_name) +# test_projfile.update_file([5], "passed", "sample_test") +# output_dict = test_projfile.as_dict() +# expected_line = line.Line(file_name, 5) +# expected_line.passed_by = ["sample_test"] +# expected_dict = {"5": expected_line.as_dict()} +# assert output_dict == expected_dict diff --git a/tests/test_spectrum_parser.py b/tests/test_spectrum_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac41d61e501f32ab3785661a2b66e92129e8862 --- /dev/null +++ b/tests/test_spectrum_parser.py @@ -0,0 +1,148 @@ +"""Include test cases on spectrum_parser module.""" +import pytest +from afluent import spectrum_parser + + +def test_spectrum_init(test_data): + """Check that spectrum initialization reassembles config and calculates scores.""" + input_config_dict = test_data["test_spectrum_init"]["input_config"] + expected_output_dict = test_data["test_spectrum_init"]["output_reassembled"] + spectrum_object = spectrum_parser.Spectrum(input_config_dict) + assert spectrum_object.totals == expected_output_dict + + +def test_spectrum_init_empty_config(): + """Check that nothing will happen when empty config is passed to + Spectrum.""" + spectrum_object = spectrum_parser.Spectrum({}) + assert not spectrum_object.reassembled_data + assert spectrum_object.totals == {"passed": 0, "failed": 0, "skipped": 0} + + +def test_spectrum_generate_report_throws_error(test_data): + """Check that error is thrown when unknown method is used.""" + config_item = test_data["test_spectrum_init"]["input_config"] + spectrum_object = spectrum_parser.Spectrum(config_item) + with pytest.raises(Exception): + spectrum_object.generate_report("random") + + +def test_spectrum_init_eval_mode(): + """Check that all tiebreaker data is generated in eval mode.""" + config = { + "test1": { + "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]}, + "result": "passed", + } + } + spectrum_object = spectrum_parser.Spectrum(config, eval_mode=True) + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].cyclomatic_complexity_data + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].logical_tiebreak_data + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].enhanced_tiebreak_data + + +def test_spectrum_init_enhanced_tiebreaker(): + """Check that only the data for the enhanced tiebreaker is calculated for + that mode.""" + config = { + "test1": { + "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]}, + "result": "passed", + } + } + spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="enhanced") + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].cyclomatic_complexity_data + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].logical_tiebreak_data + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].enhanced_tiebreak_data + + +def test_spectrum_init_logical_tiebreaker(): + """Check that only the data for the logical tiebreaker is calculated for + that mode.""" + config = { + "test1": { + "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]}, + "result": "passed", + } + } + spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="logical") + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].cyclomatic_complexity_data + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].logical_tiebreak_data + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].enhanced_tiebreak_data + + +def test_spectrum_init_cyclomatic_tiebreaker(): + """Check that only the data for the cyclomatic tiebreaker is calculated for + that mode.""" + config = { + "test1": { + "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]}, + "result": "passed", + } + } + spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="cyclomatic") + assert spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].cyclomatic_complexity_data + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].logical_tiebreak_data + assert not spectrum_object.reassembled_data[ + "tests/test_data/sample_file.py" + ].enhanced_tiebreak_data + + +def test_spectrum_print_report_throws_error(): + """Check that an error is thrown when an unknown report is requested.""" + config = { + "test1": { + "coverage": {"tests/test_data/sample_file.py": [1, 2, 3, 4]}, + "result": "passed", + } + } + spectrum_object = spectrum_parser.Spectrum(config, tiebreaker="cyclomatic") + with pytest.raises(Exception): + spectrum_object.print_report(["something"], items_num=20) + + +@pytest.mark.parametrize( + "method,sus_score,rank,out_of,formatting_func", + [ + ("tarantula", 0, 1, 1, spectrum_parser.PALETTE["safe"]), + ("tarantula", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]), + ("tarantula", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]), + ("tarantula", 1, 8, 20, spectrum_parser.PALETTE["severe"]), + ("ochiai", 0, 1, 1, spectrum_parser.PALETTE["safe"]), + ("ochiai", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]), + ("ochiai", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]), + ("ochiai", 1, 8, 20, spectrum_parser.PALETTE["severe"]), + ("dstar", 0, 1, 1, spectrum_parser.PALETTE["safe"]), + ("dstar", 0.5, 1, 20, spectrum_parser.PALETTE["risky"]), + ("dstar", 0.5, 16, 20, spectrum_parser.PALETTE["mild"]), + ("dstar", float("inf"), 8, 20, spectrum_parser.PALETTE["severe"]), + ], +) +def test_calculate_severity(method, sus_score, rank, out_of, formatting_func): + """Check that severity calculating returns the correct formatting function.""" + assert ( + spectrum_parser.Spectrum.calculate_severity(method, sus_score, rank, out_of) + == formatting_func + )