Example #1
0
def _make_as_diagnostics(report):
    """Format a report as TAP diagnostic output."""
    out = StringIO()
    tw = TerminalWriter(file=out)
    report.toterminal(tw)
    lines = out.getvalue().splitlines(True)
    return format_as_diagnostics(lines)
Example #2
0
def mutate_class(child, output_file_name):
    ''' Set current_class and call mutate_function for all methods of the class '''
    global current_class
    global all_mutants

    if not any(func_name.startswith(child.name.value) for func_name in all_mutants.keys()):
        return

    TerminalWriter().sep(".", child.name.value)

    current_class = child
    for c in child.get_suite().children:
        if c.type == "funcdef":
            mutate_function(c, output_file_name)
    current_class = None

    TerminalWriter().sep(".")
Example #3
0
 def __init__(self, file):
     super(TerminalWriterWrapper, self).__init__()
     if config.root.log.color_console is not None:
         os.environ[
             'PY_COLORS'] = '1' if config.root.log.color_console else '0'
     self._writer = TerminalWriter(file=file)
     self._isatty = file.isatty()
     self._line = ''
def _get_error_contents_from_report(report):
    if report.longrepr is not None:
        tw = TerminalWriter(stringio=True)
        tw.hasmarkup = False
        report.toterminal(tw)
        exc = tw.stringio.getvalue()
        s = exc.strip()
        if s:
            return s

    return ''
Example #5
0
def mutate_file(input_file_path, output_file_name, module_path, reset):
    '''
    Find the mutants in the input file and write the ones chosen by the user to the output file
    '''
    global all_mutants

    input_file = open(input_file_path, "r")
    content = input_file.read()
    input_file.close()

    TerminalWriter().sep("=", path.basename(input_file_path))

    write_imports = True
    if path.isfile(output_file_name) and not reset:
        write_imports = False
        print(CYAN + "The file", output_file_name, "already exists.")
        print("\t(r) reset")
        print("\t(c) continue where it stopped")
        print("\t(a) abort" + RESET)
        answer = input()
        while answer not in ["r", "a", "c"]:
            answer = input("Invalid choice, try again: ")

        if answer == "r":   # reset
            write_imports = True
        elif answer == "a": # abort
            return
        elif answer == "c": # continue
            check_already_written(output_file_name)

    all_mutants = {}
    tree = parso.parse(content)
    find_mutants(tree)
    if len(all_mutants) == 0:
        return

    if write_imports:
        output_file = open(output_file_name, "w")
        output_file.write("import pytest_mutagen as mg\n")
        output_file.write("import " + path.basename(path.normpath(module_path)) + "\n")
        output_file.write("from " + make_valid_import(input_file.name, module_path) + " import ")
        output_file.write(", ".join(get_imports()))
        output_file.write("\n\n")
        output_file.write("mg.link_to_file(mg.APPLY_TO_ALL)\n\n")
        output_file.close()

    for child in tree.children:
        if child.type == "funcdef":
            mutate_function(child, output_file_name)
        elif child.type == "classdef":
            mutate_class(child, output_file_name)

    print("Mutants written to", output_file_name)
    all_mutants = {}
Example #6
0
    def __init__(self, config=None, file=None):
        if config:
            # If we have a config, nothing more needs to be done
            return TerminalReporter.__init__(self, config, file)

        # Without a config, pretend to be a TerminalReporter
        # hook-related functions (logreport, collection, etc) will be outrigt broken,
        # but the line writers should still be usable
        if file is None:
            file = sys.stdout

        self._tw = self.writer = TerminalWriter(file)
        self.hasmarkup = self._tw.hasmarkup
        self.reportchars = ''
        self.currentfspath = None
Example #7
0
def pytest_sessionfinish(session, exitstatus):
    """Handle the end of the session."""
    n = session.config.option.durations
    if n is None:
        return
    print('\n')
    try:
        import pytest_harvest
    except ImportError:
        print('Module-level timings require pytest-harvest')
        return
    from py.io import TerminalWriter
    # get the number to print
    res = pytest_harvest.get_session_synthesis_dct(session)
    files = dict()
    for key, val in res.items():
        parts = Path(key.split(':')[0]).parts
        # split mne/tests/test_whatever.py into separate categories since these
        # are essentially submodule-level tests. Keeping just [:3] works,
        # except for mne/viz where we want level-4 granulatity
        split_submodules = (('mne', 'viz'), ('mne', 'preprocessing'))
        parts = parts[:4 if parts[:2] in split_submodules else 3]
        if not parts[-1].endswith('.py'):
            parts = parts + ('', )
        file_key = '/'.join(parts)
        files[file_key] = files.get(file_key, 0) + val['pytest_duration_s']
    files = sorted(list(files.items()), key=lambda x: x[1])[::-1]
    # print
    files = files[:n]
    if len(files):
        writer = TerminalWriter()
        writer.line()  # newline
        writer.sep('=', f'slowest {n} test module{_pl(n)}')
        names, timings = zip(*files)
        timings = [f'{timing:0.2f}s total' for timing in timings]
        rjust = max(len(timing) for timing in timings)
        timings = [timing.rjust(rjust) for timing in timings]
        for name, timing in zip(names, timings):
            writer.line(f'{timing.ljust(15)}{name}')
Example #8
0
 def __init__(self, terminal_writer=TerminalWriter()):
     self.terminal_writer = terminal_writer