class Script(object): _title = 'Base Script' _message = 'Instructions' _verbose_log_filename = os.path.join('logs', 'verbose.log') _failure_log_filename = os.path.join('logs', 'failure.log') _overview_log_filename = os.path.join('logs', 'overview.log') def __init__(self): self._logger = setup_logging() self._tw = TerminalWriter() self._tw.sep('#', self._title, green=True, bold=True) self._client = TCClient() self._logger.info( 'Great! Let\'s get this going!' ' _ _ _\n' ' >(.)__ <(.)__ =(.)__\n' ' (___/ (___/ (___/ \n' ) self._logger = setup_logging(self._verbose_log_filename, debug=True) self._fail_logger = setup_logging(self._failure_log_filename, name='failures') self._overview_logger = setup_logging(self._overview_log_filename, name='overview') self._client = TCClient() def run(self): self._tw.sep('#', 'Process Complete!', green=True, bold=True) def get_user_id_from_email_address(self, email): user = self._client.get_user_by_email(email) if user is None: self._fail_logger.warning('No user with login %s. Could not deprovision.', email) self._overview_logger.warning('No user with login %s. Could not deprovision.', email) return None return user.id
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 ''
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)
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(".")
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 = {}
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
def __init__(self): self._logger = setup_logging() self._tw = TerminalWriter() self._tw.sep('#', self._title, green=True, bold=True) self._client = TCClient() self._logger.info( 'Great! Let\'s get this going!' ' _ _ _\n' ' >(.)__ <(.)__ =(.)__\n' ' (___/ (___/ (___/ \n' ) self._logger = setup_logging(self._verbose_log_filename, debug=True) self._fail_logger = setup_logging(self._failure_log_filename, name='failures') self._overview_logger = setup_logging(self._overview_log_filename, name='overview') self._client = TCClient()
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}')
class TerminalWriterWrapper(object): 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 isatty(self): return self._isatty def _get_full_width(self): fullwidth = self._writer.fullwidth if sys.platform == "win32": # see py.io documentation for an explanation fullwidth -= 1 # pragma: no cover return fullwidth def lsep(self, sep, msg, **kw): """Write a left-justified line filled with the separator until the end of the line""" self._do_write( '{0} {1}\n'.format( msg, sep * ((self._get_full_width() - 1 - len(msg)) // len(sep))), **kw) def write_box(self, headline, msg, **kw): box_width = min(self._get_full_width(), 60) line_width = box_width - 4 max_headline_length = box_width - 6 if len(headline) > max_headline_length: headline = headline[max_headline_length:] def write_line(line_to_write): eol_padding = box_width - (len(line_to_write) + 3) self._do_write( '* {0}{1}*\n'.format(line_to_write, ' ' * eol_padding), **kw) self._do_write( '\n** {0} {1}\n'.format(headline, '*' * (box_width - (len(headline) + 4))), **kw) for line in msg.split('\n'): if not line: write_line('') else: for sub_line in wrap(line, line_width): write_line(sub_line) self._do_write('{0}\n\n'.format('*' * box_width), **kw) def sep(self, *args, **kw): self._line = '' return self._writer.sep(*args, **kw) def write(self, line, **kw): line = str(line) self._do_write(line, **kw) self._line = self._get_line_remainder(self._line + line) def _get_line_remainder(self, line): return line.rsplit('\r', 1)[-1].rsplit('\n', 1)[-1] def line(self, *args, **kw): self._writer.line(*args, **kw) self._line = '' def clear_line_in_progress(self): if self._line and self._writer.hasmarkup: self._do_write('\r') self._do_write(' ' * (len(self._line) % self._writer.fullwidth)) self._do_write('\r') def restore_line_in_progress(self): if self._writer.hasmarkup: idx = len(self._line) - (len(self._line) % self._writer.fullwidth) self._do_write(self._line[idx:]) def _do_write(self, *args, **kwargs): return self._writer.write(*args, **kwargs)
def __init__(self, file): super(TerminalWriterWrapper, self).__init__() self._writer = TerminalWriter(file=file) self._isatty = file.isatty() self._line = ''
class TerminalWriterWrapper(object): def __init__(self, file): super(TerminalWriterWrapper, self).__init__() self._writer = TerminalWriter(file=file) self._isatty = file.isatty() self._line = '' def isatty(self): return self._isatty def _get_full_width(self): fullwidth = self._writer.fullwidth if sys.platform == "win32": # see py.io documentation for an explanation fullwidth -= 1 return fullwidth def lsep(self, sep, msg, **kw): """Write a left-justified line filled with the separator until the end of the line""" self._do_write( '{0} {1}\n'.format(msg, sep * ((self._get_full_width() - 1 - len(msg)) // len(sep))), **kw) def write_box(self, headline, msg, **kw): box_width = min(self._get_full_width(), 60) line_width = box_width - 4 max_headline_length = box_width - 6 if len(headline) > max_headline_length: headline = headline[max_headline_length:] def write_line(line_to_write): eol_padding = box_width - (len(line_to_write) + 3) self._do_write('* {0}{1}*\n'.format(line_to_write, ' ' * eol_padding), **kw) self._do_write('\n** {0} {1}\n'.format(headline, '*' * (box_width - (len(headline) + 4))), **kw) for line in msg.split('\n'): if not line: write_line('') else: for sub_line in wrap(line, line_width): write_line(sub_line) self._do_write('{0}\n\n'.format('*' * box_width), **kw) def sep(self, *args, **kw): self._line = '' return self._writer.sep(*args, **kw) def write(self, line, **kw): line = str(line) self._do_write(line, **kw) self._line = self._get_line_remainder(self._line + line) def _get_line_remainder(self, line): return line.rsplit('\r', 1)[-1].rsplit('\n', 1)[-1] def line(self, *args, **kw): self._writer.line(*args, **kw) self._line = '' def get_line_in_progress(self): return self._line def clear_line_in_progress(self): if self._line and self._writer.hasmarkup: self._do_write('\r') self._do_write(' ' * len(self._line)) self._do_write('\r') def restore_line_in_progress(self): if self._writer.hasmarkup: self._do_write(self._line) def _do_write(self, *args, **kwargs): return self._writer.write(*args, **kwargs)
class TerminalWriterWrapper(object): def __init__(self, file): super(TerminalWriterWrapper, self).__init__() self._writer = TerminalWriter(file=file) self._line = '' def sep(self, *args, **kw): self._line = '' return self._writer.sep(*args, **kw) def write(self, line, **kw): line = str(line) self._writer.write(line, **kw) if '\n' in line: line = line.rsplit('\n', 1)[-1].rsplit('\r', 1)[-1] self._line = line else: self._line += line def line(self, *args, **kw): self._writer.line(*args, **kw) self._line = '' def get_line_in_progress(self): return self._line def clear_line_in_progress(self): if self._line and self._writer.hasmarkup: self._writer.write('\r') self._writer.write(' ' * len(self._line)) self._writer.write('\r') def restore_line_in_progress(self): if self._writer.hasmarkup: self._writer.write(self._line)
def __init__(self, terminal_writer=TerminalWriter()): self.terminal_writer = terminal_writer