How to use _verobsity_allows method in Slash

Best Python code snippet using slash

console_reporter.py

Source:console_reporter.py Github

copy

Full Screen

...24def from_verbosity(level):25 def decorator(func):26 @wraps(func)27 def new_func(self, *args, **kwargs):28 if self._verobsity_allows(level): # pylint: disable=protected-access29 return func(self, *args, **kwargs)30 return new_func31 return decorator32def swallowing_terminal_exceptions(func):33 @functools.wraps(func)34 def inner(*args, **kwargs):35 try:36 return func(*args, **kwargs)37 except (IOError, OSError):38 pass39 return inner40class TerminalWriterWrapper(object):41 def __init__(self, file):42 super(TerminalWriterWrapper, self).__init__()43 if config.root.log.color_console is not None:44 os.environ['PY_COLORS'] = '1' if config.root.log.color_console else '0'45 self._writer = TerminalWriter(file=file)46 self._isatty = file.isatty()47 self._line = ''48 def isatty(self):49 return self._isatty50 def _get_full_width(self):51 fullwidth = self._writer.fullwidth52 if sys.platform == "win32":53 # see py.io documentation for an explanation54 fullwidth -= 1 # pragma: no cover55 return fullwidth56 def lsep(self, sep, msg, **kw):57 """Write a left-justified line filled with the separator until the end of the line"""58 self._do_write(59 '{} {}\n'.format(msg, sep * ((self._get_full_width() - 1 - len(msg)) // len(sep))), **kw)60 def write_box(self, headline, msg, **kw):61 box_width = min(self._get_full_width(), 60)62 line_width = box_width - 463 max_headline_length = box_width - 664 if len(headline) > max_headline_length:65 headline = headline[max_headline_length:]66 def write_line(line_to_write):67 eol_padding = box_width - (len(line_to_write) + 3)68 self._do_write('* {}{}*\n'.format(line_to_write, ' ' * eol_padding), **kw)69 self._do_write('\n** {} {}\n'.format(headline, '*' * (box_width - (len(headline) + 4))), **kw)70 for line in msg.split('\n'):71 if not line:72 write_line('')73 else:74 for sub_line in wrap(line, line_width):75 write_line(sub_line)76 self._do_write('{}\n\n'.format('*' * box_width), **kw)77 @swallowing_terminal_exceptions78 def sep(self, *args, **kw):79 self._line = ''80 return self._writer.sep(*args, **kw)81 def write(self, line, **kw):82 line = str(line)83 self._do_write(line, **kw)84 self._line = self._get_line_remainder(self._line + line)85 def _get_line_remainder(self, line):86 return line.rsplit('\r', 1)[-1].rsplit('\n', 1)[-1]87 @swallowing_terminal_exceptions88 def line(self, *args, **kw):89 self._writer.line(*args, **kw)90 self._line = ''91 def clear_line_in_progress(self):92 if self._line and self._writer.hasmarkup:93 self._do_write('\r')94 self._do_write(' ' * (len(self._line) % self._writer.fullwidth))95 self._do_write('\r')96 def restore_line_in_progress(self):97 if self._writer.hasmarkup:98 idx = len(self._line) - (len(self._line) % self._writer.fullwidth)99 self._do_write(self._line[idx:])100 @swallowing_terminal_exceptions101 def _do_write(self, *args, **kwargs):102 return self._writer.write(*args, **kwargs)103class ConsoleReporter(ReporterInterface):104 def __init__(self, level, stream=sys.stderr):105 super(ConsoleReporter, self).__init__()106 self._level = level107 self._stream = stream108 self._terminal = TerminalWriterWrapper(file=stream)109 def notify_before_console_output(self):110 self._terminal.clear_line_in_progress()111 def notify_after_console_output(self):112 self._terminal.restore_line_in_progress()113 def report_before_debugger(self, exc_info):114 self.notify_before_console_output()115 self._terminal.write('Exception caught in debugger: {} {}\n'.format(116 exc_info[0], exc_info[1]), **theme('inline-error'))117 self.notify_after_console_output()118 def report_collection_start(self):119 self._report_num_collected([], stillworking=True)120 def report_test_collected(self, all_tests, test):121 self._report_num_collected(all_tests, stillworking=True)122 def report_collection_end(self, collected):123 self._report_num_collected(collected, stillworking=False)124 def _report_num_collected(self, collected, stillworking):125 if self._terminal.isatty():126 self._terminal.write('\r')127 elif stillworking:128 return129 self._terminal.write('{} tests collected{}'.format(130 len(collected), '...' if stillworking else ' \n'), **theme('num-collected'))131 def _is_verbose(self, level):132 return self._level <= level133 @from_verbosity(VERBOSITIES.ERROR)134 def report_session_start(self, session):135 self._terminal.sep('=', 'Session starts', **theme('session-start'))136 def report_session_end(self, session):137 if not self._verobsity_allows(VERBOSITIES.WARNING):138 # for concise outputs we need to break the sequence of dots...139 self._terminal.write('\n')140 header_format = self._get_session_summary_header_format(session)141 for index, (test_index, test_result, infos) in enumerate(self._iter_reported_results(session)):142 if index == 0:143 self._terminal.sep('=', 'Session Summary', **header_format)144 self._report_test_summary_header(test_index, test_result)145 self._report_additional_test_details(test_result)146 for info_reporter in infos:147 info_reporter(test_result)148 if self._verobsity_allows(VERBOSITIES.WARNING):149 self._report_result_warning_summary(session)150 msg = 'Session ended.'151 msg += ' {} successful, {} skipped, {} failed, {} erroneous.'.format(152 session.results.get_num_successful(153 ), session.results.get_num_skipped(include_not_run=False),154 session.results.get_num_failures(), session.results.get_num_errors())155 not_run = session.results.get_num_not_run()156 if not_run:157 msg += ' {} not run.'.format(not_run)158 if (session.has_children() and session.parallel_manager.server159 and session.parallel_manager.server.worker_error_reported):160 msg += " Found session errors in children."161 msg += ' Total duration: {}'.format(162 self._format_duration(session.duration))163 self._terminal.sep('=', msg, **header_format)164 def _get_session_summary_header_format(self, session):165 if session.results.is_success(allow_skips=True):166 return theme('session-summary-success')167 return theme('session-summary-failure')168 def _iter_reported_results(self, session):169 for test_index, test_result in enumerate(session.results.iter_test_results()):170 infos = self._get_result_info_generators(test_result)171 if not infos:172 continue173 yield test_index, test_result, infos174 def _report_test_summary_header(self, index, test_result):175 self._terminal.lsep(176 "=", '== #{}: {}'.format(index + 1, test_result.test_metadata.address), **theme('test-error-header'))177 def _get_result_info_generators(self, test_result):178 returned = []179 if self._verobsity_allows(VERBOSITIES.ERROR) and test_result.has_errors_or_failures():180 returned.append(self._report_result_errors_failures)181 if self._verobsity_allows(VERBOSITIES.INFO) and test_result.has_skips():182 returned.append(self._report_result_skip_summary)183 return returned184 def _report_result_warning_summary(self, session):185 warnings_by_key = {}186 for warning in session.warnings:187 warnings_by_key.setdefault(warning.key, []).append(warning)188 for i, warnings in iteration(warnings_by_key.values()):189 if i.first:190 self._terminal.sep(191 '=', 'Warnings ({} total)'.format(len(session.warnings)), yellow=True)192 self._terminal.write(193 ' * {d[filename]}:{d[lineno]:03} -- '.format(d=warnings[0].details), yellow=True)194 self._terminal.write(195 warnings[0].details['message'], yellow=True, bold=True)196 self._terminal.write(197 ' (Repeated {} times)\n'.format(len(warnings)), yellow=True)198 def _verobsity_allows(self, level):199 return self._level <= level200 def _report_result_errors_failures(self, test_result):201 all_errs = list(202 itertools.chain(zip(itertools.repeat("E"), test_result.get_errors()),203 zip(itertools.repeat("F"), test_result.get_failures())))204 for index, (err_type, err) in enumerate(all_errs):205 if err.exception_type is None and not config.root.log.show_manual_errors_tb:206 self._terminal.write(err.message, **theme('tb-error'))207 self._terminal.write('\n')208 continue209 err_header = ' - {0}/{1} {2} ({3:YYYY-MM-DD HH:mm:ss ZZ}): {4}'.format(210 index + 1,211 len(all_errs),212 err_type,213 err.time.to('local'),214 ' - {}'.format(err.message) if not err.traceback else '')215 self._terminal.lsep(' -', err_header, **theme('error-separator-dash'))216 if err.has_custom_message():217 self._terminal.write(' {}\n'.format(err.message), **theme('tb-error-message'))218 self._report_traceback(err_type, err)219 def _report_traceback(self, err_type, err):220 console_traceback_level = config.root.log.console_traceback_level221 if not err.traceback or console_traceback_level == NO_TRACEBACK:222 frames = []223 elif console_traceback_level == SINGLE_FRAME:224 frames = [err.traceback.frames[-1]]225 else:226 frames = err.traceback.frames227 for frame_iteration, frame in iteration(frames):228 if console_traceback_level >= ALL_FRAMES_WITH_CONTEXT_AND_VARS:229 if not frame_iteration.first:230 self._terminal.sep('- ')231 self._terminal.write(232 ' {}:{}\n'.format(frame.filename, frame.lineno), **theme('tb-frame-location'))233 if console_traceback_level >= ALL_FRAMES_WITH_CONTEXT_AND_VARS:234 self._write_frame_locals(frame)235 self._write_frame_code(236 frame, include_context=(console_traceback_level >= ALL_FRAMES_WITH_CONTEXT))237 if frame_iteration.last:238 self._terminal.write(err_type, **theme('tb-error'))239 self._terminal.write(240 self._indent_with(err.message, 4), **theme('tb-error'))241 self._terminal.write('\n')242 def _report_additional_test_details(self, result):243 if result.is_success():244 return245 detail_items = result.details.all().items()246 log_path = result.get_log_path()247 if log_path is not None:248 detail_items = itertools.chain(detail_items, [('Log', log_path)])249 for index, (key, value) in enumerate(detail_items):250 if index == 0:251 self._terminal.write(' - Additional Details:\n', **theme('test-additional-details-header'))252 self._terminal.write(' > {}: {!r}\n'.format(key, value), **theme('test-additional-details'))253 def _indent_with(self, text, indent):254 if isinstance(indent, int):255 indent = ' ' * indent256 return '\n'.join(indent + line for line in text.splitlines())257 def _report_result_skip_summary(self, result):258 msg = '\tSkipped'259 skip_reasons = [r for r in result.get_skips() if r is not None]260 if skip_reasons:261 msg += ' ({})'.format(', '.join(skip_reasons))262 msg += '\n'263 self._terminal.write(msg, **theme('test-skip-message'))264 def _write_frame_locals(self, frame):265 with vintage.get_no_deprecations_context():266 locals = frame.locals267 globals = frame.globals268 if not locals and not globals:269 return270 for index, (name, value) in enumerate(itertools.chain(locals.items(), globals.items())):271 if index > 0:272 self._terminal.write(', ')273 self._terminal.write(274 ' {}: '.format(name), **theme('frame-local-varname'))275 self._terminal.write(value['value'])276 self._terminal.write('\n\n')277 def _write_frame_code(self, frame, include_context):278 if frame.code_string:279 if include_context:280 code_lines = frame.code_string.splitlines()281 else:282 code_lines = [frame.code_line]283 line = ''284 for line_iteration, line in iteration(code_lines):285 if line_iteration.last:286 self._terminal.write('>', **theme('error-cause-marker'))287 else:288 self._terminal.write(' ')289 if frame.is_in_test_code():290 theme_name = 'tb-test-line'291 elif line_iteration.last:292 theme_name = 'tb-line-cause'293 else:294 theme_name = 'tb-line'295 self._terminal.write(line, **theme(theme_name))296 self._terminal.write('\n')297 return code_lines298 @from_verbosity(VERBOSITIES.WARNING)299 def report_file_start(self, filename):300 self._file_failed = False301 self._file_has_skips = False302 if not self._verobsity_allows(VERBOSITIES.NOTICE):303 self._terminal.write(filename)304 self._terminal.write(' ')305 @from_verbosity(VERBOSITIES.WARNING)306 def report_file_end(self, filename):307 if self._verobsity_allows(VERBOSITIES.NOTICE):308 return309 self._terminal.write(' ')310 if self._file_failed:311 self._terminal.line('FAIL', **theme('inline-file-end-fail'))312 elif self._file_has_skips:313 self._terminal.line('PASS', **theme('inline-file-end-skip'))314 else:315 self._terminal.line('PASS', **theme('inline-file-end-success'))316 def report_test_success(self, test, result):317 if not self._verobsity_allows(VERBOSITIES.NOTICE):318 self._terminal.write('.')319 def report_test_skip_added(self, test, reason):320 self._file_has_skips = True321 if self._verobsity_allows(VERBOSITIES.NOTICE):322 self._terminal.write('Skipped: {}, Test: {}\n'.format(reason, test.__slash__), **theme('test-skip-message'))323 else:324 self._terminal.write('s', yellow=True)325 def report_test_interrupted(self, test, result):326 if self._verobsity_allows(VERBOSITIES.NOTICE):327 self._terminal.write('Interrupted\n', **theme('inline-test-interrupted'))328 else:329 self._terminal.write('I', **theme('inline-test-interrupted'))330 def report_test_error_added(self, test, error):331 self._report_test_error_failure_added(test, error, 'E')332 def report_test_failure_added(self, test, error):333 self._report_test_error_failure_added(test, error, 'F')334 def _report_test_error_failure_added(self, test, e, errtype): # pylint: disable=unused-argument335 if test is None:336 if e.exception_type is None or not issubclass(e.exception_type, CLI_ABORT_EXCEPTIONS):337 self._terminal.line('Session error caught -- {}\n'.format(e), **theme('inline-error'))338 else:339 self._file_failed = True340 if not self._verobsity_allows(VERBOSITIES.NOTICE):341 self._terminal.write(errtype, red=True)342 else:343 self._terminal.write('{}: {}, Test: {}\n'.format(errtype, e, test.__slash__), **theme('inline-error'))344 def report_fancy_message(self, headline, message):345 if self._verobsity_allows(VERBOSITIES.INFO):346 self._terminal.write_box(headline, message, **theme('fancy-message'))347 def report_message(self, message):348 self.notify_before_console_output()349 self._terminal.write(message)350 self._terminal.write('\n')351 self.notify_after_console_output()352 def report_error_message(self, message):353 self.notify_before_console_output()354 self._terminal.write('ERROR: {}'.format(message), **theme('inline-error'))355 self._terminal.write('\n')356 self.notify_after_console_output()357 def _format_duration(self, duration):358 seconds = duration % 60359 duration /= 60...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful