Best Python code snippet using lemoncheesecake
console.py
Source:console.py  
1'''2Created on Mar 19, 20163@author: nicolas4'''5from __future__ import print_function6import sys7from termcolor import colored8import six9from lemoncheesecake.testtree import filter_suites, flatten_suites10from lemoncheesecake.reporting.backend import ReportingBackend, ReportingSession, ReportingSessionBuilderMixin11from lemoncheesecake.reporting.report import ReportStats12from lemoncheesecake.helpers.time import humanize_duration13from lemoncheesecake.helpers.text import ensure_single_line_text14from lemoncheesecake.helpers import terminalsize15from lemoncheesecake.reporting.console import test_status_to_color16class LinePrinter:17    def __init__(self, terminal_width):18        self.terminal_width = terminal_width19        self.prev_len = 020    def print_line(self, line, force_len=None):21        value_len = force_len if force_len else len(line)22        if six.PY2:23            if type(line) is unicode:24                line = line.encode("utf-8")25        if value_len >= self.terminal_width - 1:26            line = line[:self.terminal_width - 5] + "..."27            value_len = len(line)28        sys.stdout.write("\r")29        sys.stdout.write(line)30        if self.prev_len > value_len:31            sys.stdout.write(" " * (self.prev_len - value_len))32        sys.stdout.flush()33        self.prev_len = value_len34    def new_line(self):35        self.prev_len = 036        sys.stdout.write("\n")37        sys.stdout.flush()38    def erase_line(self):39        sys.stdout.write("\r")40        sys.stdout.write(" " * self.prev_len)41        sys.stdout.write("\r")42        self.prev_len = 043def _make_suite_header_line(suite, terminal_width):44    suite_name = suite.path45    max_width = min((terminal_width, 80))46    # -2 corresponds to the two space characters at the left and right of suite path + another character to avoid47    # an extra line after the suite line on Windows terminal having width <= 8048    padding_total = max_width - 3 - len(suite_name) if len(suite_name) <= (max_width - 3) else 049    padding_left = padding_total // 250    padding_right = padding_total // 2 + padding_total % 251    return "=" * padding_left + " " + colored(suite_name, attrs=["bold"]) + " " + "=" * padding_right52def _make_test_status_label(status):53    if status == "passed":54        label = "OK"55    elif status in ("skipped", "disabled", None):56        label = "--"57    else:58        label = "KO"59    return colored(label, test_status_to_color(status), attrs=["bold"])60def _make_test_result_line(name, num, status):61    line = " %s %2s # %s" % (_make_test_status_label(status), num, name)62    raw_line = "%s %2s # %s" % ("OK" if status == "passed" else "KO", num, name)63    return line, len(raw_line)64def _print_summary(stats, parallel=False):65    print()66    print(colored("Statistics", attrs=["bold"]), ":")67    print(" * Duration: %s" % (humanize_duration(stats.duration) if stats.duration is not None else "n/a"))68    if parallel:69        print(" * Cumulative duration: %s" % stats.duration_cumulative_description)70    print(" * Tests: %d" % stats.tests_nb)71    print(" * Successes: %d (%d%%)" % (stats.tests_nb_by_status["passed"], stats.successful_tests_percentage))72    print(" * Failures: %d" % (stats.tests_nb_by_status["failed"]))73    if stats.tests_nb_by_status["skipped"]:74        print(" * Skipped: %d" % (stats.tests_nb_by_status["skipped"]))75    if stats.tests_nb_by_status["disabled"]:76        print(" * Disabled: %d" % (stats.tests_nb_by_status["disabled"]))77    print()78class SequentialConsoleReportingSession(ReportingSession):79    def __init__(self, terminal_width, show_test_full_path, report):80        self.terminal_width = terminal_width81        self.show_test_full_path = show_test_full_path82        self.report = report83        self.lp = LinePrinter(self.terminal_width)84        self.context = None85        self.custom_step_prefix = None86        self.current_suite = None87    def get_test_label(self, test):88        if self.show_test_full_path:89            return test.path90        return test.name91    def ensure_suite_header_is_displayed(self, suite):92        if suite == self.current_suite:93            return94        self.current_suite = suite95        self.current_test_idx = 196        if self.previous_obj:97            sys.stdout.write("\n")98        sys.stdout.write(_make_suite_header_line(suite, self.terminal_width) + "\n")99        self.previous_obj = suite100    def on_test_session_start(self, event):101        self.previous_obj = None102    def on_suite_setup_start(self, event):103        self.ensure_suite_header_is_displayed(event.suite)104        self.step_prefix = " => setup suite: "105        self.lp.print_line(self.step_prefix + "...")106    def on_suite_teardown_start(self, event):107        self.step_prefix = " => teardown suite: "108        self.lp.print_line(self.step_prefix + "...")109    def on_test_session_setup_start(self, event):110        self.step_prefix = " => setup test session: "111        self.lp.print_line(self.step_prefix + "...")112    def on_test_session_teardown_start(self, event):113        self.step_prefix = " => teardown test session: "114        self.lp.print_line(self.step_prefix + "...")115    def on_suite_setup_end(self, event):116        self.lp.erase_line()117        self.custom_step_prefix = None118    on_suite_teardown_end = on_suite_setup_end119    def on_test_session_setup_end(self, event):120        self.lp.erase_line()121        self.custom_step_prefix = None122    on_test_session_teardown_end = on_test_session_setup_end123    def on_test_start(self, event):124        self.ensure_suite_header_is_displayed(event.test.parent_suite)125        self.step_prefix = " -- %2s # %s" % (self.current_test_idx, self.get_test_label(event.test))126        self.lp.print_line(self.step_prefix + "...")127        self.previous_obj = event.test128    def on_test_end(self, event):129        test_data = self.report.get_test(event.test)130        line, raw_line_len = _make_test_result_line(131            self.get_test_label(event.test), self.current_test_idx, test_data.status132        )133        self.lp.print_line(line, force_len=raw_line_len)134        self.lp.new_line()135        self.current_test_idx += 1136    def _bypass_test(self, test, status):137        self.ensure_suite_header_is_displayed(test.parent_suite)138        line = " %s %2s # %s" % (_make_test_status_label(status), self.current_test_idx, self.get_test_label(test))139        raw_line = "%s %2s # %s" % ("KO", self.current_test_idx, self.get_test_label(test))140        self.lp.print_line(line, force_len=len(raw_line))141        self.lp.new_line()142        self.current_test_idx += 1143    def on_test_skipped(self, event):144        self._bypass_test(event.test, "skipped")145    def on_test_disabled(self, event):146        self._bypass_test(event.test, "disabled")147    def on_step_start(self, event):148        self.lp.print_line("%s (%s...)" % (self.step_prefix, ensure_single_line_text(event.step_description)))149    def on_test_session_end(self, event):150        _print_summary(ReportStats.from_report(self.report), self.report.parallelized)151class ParallelConsoleReportingSession(ReportingSession):152    def __init__(self, terminal_width, report):153        self.terminal_width = terminal_width154        self.report = report155        self.lp = LinePrinter(self.terminal_width)156        self.current_test_idx = 1157    def on_test_end(self, event):158        test_data = self.report.get_test(event.test)159        line, _ = _make_test_result_line(160            event.test.path, self.current_test_idx, test_data.status161        )162        print(line)163        self.current_test_idx += 1164    def _bypass_test(self, test, status):165        line = " %s %2s # %s" % (_make_test_status_label(status), self.current_test_idx, test.path)166        print(line)167        self.current_test_idx += 1168    def on_test_skipped(self, event):169        self._bypass_test(event.test, "skipped")170    def on_test_disabled(self, event):171        self._bypass_test(event.test, "disabled")172    def on_test_session_end(self, event):173        _print_summary(ReportStats.from_report(self.report), self.report.parallelized)174class ConsoleBackend(ReportingBackend, ReportingSessionBuilderMixin):175    def __init__(self):176        width, height = terminalsize.get_terminal_size()177        self.terminal_width = width178        self.show_test_full_path = True179    def get_name(self):180        return "console"181    def create_reporting_session(self, report_dir, report, parallel, saving_strategy):182        return \183            ParallelConsoleReportingSession(self.terminal_width, report) if parallel else \184            SequentialConsoleReportingSession(self.terminal_width, self.show_test_full_path, report)185def print_report_as_test_run(report, test_filter):186    suites = filter_suites(report.get_suites(), test_filter)187    ###188    # Setup terminal189    ###190    terminal_width, _ = terminalsize.get_terminal_size()191    ###192    # Display suite results193    ###194    suite_idx = 0195    for suite in flatten_suites(suites):196        if len(suite.get_tests()) == 0:197            continue198        if suite_idx > 0:199            print()200        header_line = _make_suite_header_line(suite, terminal_width)201        print(header_line)202        for test_idx, test in enumerate(suite.get_tests()):203            test_result_line, _ = _make_test_result_line(test.path, num=test_idx+1, status=test.status)204            print(test_result_line)205        suite_idx += 1206    ###207    # Display summary208    ###209    if suite_idx > 0:210        if test_filter:211            stats = ReportStats.from_suites(suites, report.parallelized)212        else:213            stats = ReportStats.from_report(report)214        _print_summary(stats, report.parallelized)215    else:...writer.py
Source:writer.py  
...78        self._finalize_result(suite_result.suite_setup, event.time)79    def on_suite_teardown_start(self, event):80        suite_result = self._get_suite_result(event.suite)81        suite_result.suite_teardown = self._initialize_result(event.time)82    def on_suite_teardown_end(self, event):83        suite_result = self._get_suite_result(event.suite)84        self._finalize_result(suite_result.suite_teardown, event.time)85    def on_test_start(self, event):86        test_result = self._initialize_test_result(event.test, event.time)87        suite_result = self._get_suite_result(event.test.parent_suite)88        suite_result.add_test(test_result)89    def on_test_end(self, event):90        test_result = self._get_test_result(event.test)91        self._finalize_result(test_result, event.time)92    def _bypass_test(self, test, status, status_details, time):93        test_result = self._initialize_test_result(test, time)94        test_result.end_time = time95        test_result.status = status96        test_result.status_details = status_details...backend.py
Source:backend.py  
1'''2Created on Mar 29, 20163@author: nicolas4'''5import os6from lemoncheesecake.helpers.orderedset import OrderedSet7from lemoncheesecake.exceptions import LemoncheesecakeException8_NEGATION_FLAGS = "-^~"9class ReportingSession(object):10    pass11class ReportingSessionBuilderMixin(object):12    def create_reporting_session(self, report_dir, report, parallel, report_saving_strategy):13        raise NotImplementedError()14class ReportSerializerMixin(object):15    def save_report(self, filename, report):16        raise NotImplementedError()17class ReportUnserializerMixin(object):18    def load_report(self, filename):19        raise NotImplementedError()20class ReportingBackend(object):21    def get_name(self):22        raise NotImplementedError()23    def is_available(self):24        return True25class FileReportSession(ReportingSession):26    def __init__(self, report_filename, report, reporting_backend, report_saving_strategy):27        self.report_filename = report_filename28        self.report = report29        self.reporting_backend = reporting_backend30        self.report_saving_strategy = report_saving_strategy31    def _save(self):32        self.reporting_backend.save_report(self.report_filename, self.report)33    def _handle_event(self, event):34        report_must_be_saved = self.report_saving_strategy and self.report_saving_strategy(event, self.report)35        if report_must_be_saved:36            self._save()37    on_test_session_setup_end = _handle_event38    on_test_session_teardown_end = _handle_event39    on_suite_setup_end = _handle_event40    on_suite_teardown_end = _handle_event41    on_test_end = _handle_event42    on_suite_end = _handle_event43    on_log = _handle_event44    on_log_attachment = _handle_event45    on_log_url = _handle_event46    on_check = _handle_event47    def on_test_session_end(self, event):48        # no matter what is the report_saving_strategy,49        # the report will always be saved at the end of tests50        self._save()51class FileReportBackend(ReportingBackend, ReportSerializerMixin, ReportingSessionBuilderMixin):52    def get_report_filename(self):53        raise NotImplementedError()54    def create_reporting_session(self, report_dir, report, parallel, report_saving_strategy):55        return FileReportSession(56            os.path.join(report_dir, self.get_report_filename()), report, self, report_saving_strategy57        )58def filter_available_reporting_backends(backends):59    return list(filter(lambda backend: backend.is_available(), backends))60def get_reporting_backends():61    from lemoncheesecake.reporting.backends import REPORTING_BACKENDS62    return list(63        filter(64            lambda backend: backend.is_available(),65            (backend_class() for backend_class in REPORTING_BACKENDS)66        )67    )68def get_reporting_backend_names(default_names, custom_names):69    if all(name[0] not in ("+" + _NEGATION_FLAGS) for name in custom_names):  # fixed list70        return custom_names71    elif all(name[0] in ("+" + _NEGATION_FLAGS) for name in custom_names):  # turn on/off directives72        names = OrderedSet(default_names)73        for specified_name in custom_names:74            if specified_name[0] == "+":  # turn on75                names.add(specified_name[1:])76            else:  # turn off77                try:78                    names.remove(specified_name[1:])79                except KeyError:80                    raise ValueError(81                        "reporting backend '%s' is not among the default reporting backends" % specified_name[1:]82                    )83        return names84    else:85        raise ValueError(86            "either the custom reporting backends must be fixed backend list, "87            "or a list of turn on/off (+ / ^) directives"88        )89def parse_reporting_backend_names_expression(expr):90    return list(filter(bool, expr.split(" ")))91def get_reporting_backend_by_name(name):92    try:93        return next(backend for backend in get_reporting_backends() if backend.get_name() == name)94    except StopIteration:95        raise KeyError()96def get_reporting_backends_for_test_run(available_backends, backend_names):97    backends = []98    for backend_name in backend_names:99        try:100            backend = available_backends[backend_name]101        except KeyError:102            raise LemoncheesecakeException("Unknown reporting backend '%s'" % backend_name)103        if not isinstance(backend, ReportingSessionBuilderMixin):104            raise LemoncheesecakeException("Reporting backend '%s' is not suitable for test run" % backend_name)105        backends.append(backend)...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
