How to use test_session_teardown method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

json_.py

Source:json_.py Github

copy

Full Screen

1'''2Created on Mar 27, 20163@author: nicolas4'''5import re6import json7from collections import OrderedDict8import time9import lemoncheesecake10from lemoncheesecake.reporting.backend import FileReportBackend, ReportUnserializerMixin11from lemoncheesecake.reporting.report import (12 Report, Log, Check, Attachment, Url, Step, Result, TestResult, SuiteResult,13 format_time_as_iso8601, parse_iso8601_time14)15from lemoncheesecake.exceptions import ReportLoadingError16JS_PREFIX = "var reporting_data = "17def _serialize_time(t):18 return format_time_as_iso8601(t) if t is not None else None19def _odict(*args):20 d = OrderedDict()21 i = 022 while i < len(args):23 d[args[i]] = args[i+1]24 i += 225 return d26def _serialize_steps(steps):27 json_steps = []28 for step in steps:29 json_step = _odict(30 "description", step.description,31 "start_time", _serialize_time(step.start_time),32 "end_time", _serialize_time(step.end_time),33 "entries", []34 )35 json_steps.append(json_step)36 for log in step.get_logs():37 if isinstance(log, Log):38 json_log = _odict(39 "type", "log",40 "level", log.level,41 "message", log.message,42 "time", _serialize_time(log.time)43 )44 elif isinstance(log, Attachment):45 json_log = _odict(46 "type", "attachment",47 "description", log.description,48 "filename", log.filename,49 "as_image", log.as_image,50 "time", _serialize_time(log.time)51 )52 elif isinstance(log, Url):53 json_log = _odict(54 "type", "url",55 "description", log.description,56 "url", log.url,57 "time", _serialize_time(log.time)58 )59 elif isinstance(log, Check):60 json_log = _odict(61 "type", "check",62 "description", log.description,63 "is_successful", log.is_successful,64 "details", log.details,65 "time", _serialize_time(log.time)66 )67 else:68 raise ValueError("Don't know how to handle step log %s" % log)69 json_step["entries"].append(json_log)70 return json_steps71def _serialize_node_metadata(node, json_node):72 json_node.update(_odict(73 "name", node.name, "description", node.description,74 "tags", node.tags,75 "properties", node.properties,76 "links", [_odict("name", link[1], "url", link[0]) for link in node.links]77 ))78def _serialize_result(result):79 return _odict(80 "start_time", _serialize_time(result.start_time),81 "end_time", _serialize_time(result.end_time),82 "steps", _serialize_steps(result.get_steps()),83 "status", result.status,84 "status_details", result.status_details85 )86def _serialize_test_result(test):87 json_test = _serialize_result(test)88 _serialize_node_metadata(test, json_test)89 return json_test90def _serialize_suite_result(suite):91 json_suite = _odict(92 "start_time", _serialize_time(suite.start_time),93 "end_time", _serialize_time(suite.end_time),94 "tests", list(map(_serialize_test_result, suite.get_tests())),95 "suites", list(map(_serialize_suite_result, suite.get_suites()))96 )97 _serialize_node_metadata(suite, json_suite)98 if suite.suite_setup:99 json_suite["suite_setup"] = _serialize_result(suite.suite_setup)100 if suite.suite_teardown:101 json_suite["suite_teardown"] = _serialize_result(suite.suite_teardown)102 return json_suite103def serialize_report_into_json(report):104 json_report = _odict(105 "lemoncheesecake_version", lemoncheesecake.__version__,106 "report_version", 1.1,107 "start_time", _serialize_time(report.start_time),108 "end_time", _serialize_time(report.end_time),109 "generation_time", _serialize_time(time.time()),110 "nb_threads", report.nb_threads,111 "title", report.title,112 "info", [[n, v] for n, v in report.info]113 )114 if report.test_session_setup:115 json_report["test_session_setup"] = _serialize_result(report.test_session_setup)116 json_report["suites"] = list(map(_serialize_suite_result, report.get_suites()))117 if report.test_session_teardown:118 json_report["test_session_teardown"] = _serialize_result(report.test_session_teardown)119 return json_report120def save_report_into_file(report, filename, javascript_compatibility=True, pretty_formatting=False):121 json_report = serialize_report_into_json(report)122 with open(filename, "w") as fh:123 if javascript_compatibility:124 fh.write(JS_PREFIX)125 if pretty_formatting:126 fh.write(json.dumps(json_report, indent=4))127 else:128 fh.write(json.dumps(json_report))129def _unserialize_time(t):130 return parse_iso8601_time(t) if t is not None else None131def _unserialize_step(json_step):132 step = Step(json_step["description"])133 step.start_time = _unserialize_time(json_step["start_time"])134 step.end_time = _unserialize_time(json_step["end_time"])135 for json_log in json_step["entries"]:136 if json_log["type"] == "log":137 step_log = Log(138 json_log["level"], json_log["message"], _unserialize_time(json_log["time"])139 )140 elif json_log["type"] == "attachment":141 step_log = Attachment(142 json_log["description"], json_log["filename"], json_log["as_image"],143 _unserialize_time(json_log["time"])144 )145 elif json_log["type"] == "url":146 step_log = Url(147 json_log["description"], json_log["url"], _unserialize_time(json_log["time"])148 )149 elif json_log["type"] == "check":150 step_log = Check(151 json_log["description"], json_log["is_successful"], json_log["details"],152 _unserialize_time(json_log["time"])153 )154 else:155 raise ValueError("Unknown step log type '%s'" % json_log["type"])156 step.add_log(step_log)157 return step158def _unserialize_result(json_result, result):159 result.status = json_result["status"]160 # status_details for non-test results has been introduced in report version 1.1:161 result.status_details = json_result.get("status_details", None)162 result.start_time = _unserialize_time(json_result["start_time"])163 result.end_time = _unserialize_time(json_result["end_time"])164 for json_step in json_result["steps"]:165 result.add_step(_unserialize_step(json_step))166 return result167def _unserialize_node_metadata(json_node, node):168 node.tags = json_node["tags"]169 node.properties = json_node["properties"]170 node.links = [(link["url"], link["name"]) for link in json_node["links"]]171def _unserialize_test_result(json_test):172 test = TestResult(json_test["name"], json_test["description"])173 _unserialize_result(json_test, test)174 _unserialize_node_metadata(json_test, test)175 return test176def _unserialize_suite_result(json_suite):177 suite = SuiteResult(json_suite["name"], json_suite["description"])178 _unserialize_node_metadata(json_suite, suite)179 suite.start_time = _unserialize_time(json_suite["start_time"])180 suite.end_time = _unserialize_time(json_suite["end_time"])181 if "suite_setup" in json_suite:182 suite.suite_setup = Result()183 _unserialize_result(json_suite["suite_setup"], suite.suite_setup)184 for json_test in json_suite["tests"]:185 suite.add_test(_unserialize_test_result(json_test))186 if "suite_teardown" in json_suite:187 suite.suite_teardown = Result()188 _unserialize_result(json_suite["suite_teardown"], suite.suite_teardown)189 for json_sub_suite in json_suite["suites"]:190 suite.add_suite(_unserialize_suite_result(json_sub_suite))191 return suite192def _unserialize_report(json_report):193 report = Report()194 report.title = json_report["title"]195 report.info = json_report["info"]196 report.start_time = _unserialize_time(json_report["start_time"])197 report.end_time = _unserialize_time(json_report["end_time"])198 report.saving_time = _unserialize_time(json_report["generation_time"])199 report.nb_threads = json_report["nb_threads"]200 if "test_session_setup" in json_report:201 report.test_session_setup = Result()202 _unserialize_result(json_report["test_session_setup"], report.test_session_setup)203 for json_suite in json_report["suites"]:204 report.add_suite(_unserialize_suite_result(json_suite))205 if "test_session_teardown" in json_report:206 report.test_session_teardown = Result()207 _unserialize_result(json_report["test_session_teardown"], report.test_session_teardown)208 return report209def load_report_from_file(filename):210 try:211 with open(filename, "r") as fh:212 js_content = fh.read()213 except IOError as e:214 raise e # re-raise as-is215 js_content = re.sub("^" + JS_PREFIX, "", js_content)216 try:217 js = json.loads(js_content)218 except ValueError as e:219 raise ReportLoadingError(str(e))220 report_version = js.get("report_version")221 if report_version is None:222 raise ReportLoadingError("Cannot find 'report_version' in JSON")223 if report_version >= 2.0:224 raise ReportLoadingError("Incompatible report version: got %s while 1.x is supported" % report_version)225 return _unserialize_report(js)226class JsonBackend(FileReportBackend, ReportUnserializerMixin):227 def __init__(self, javascript_compatibility=True, pretty_formatting=False):228 self.javascript_compatibility = javascript_compatibility229 self.pretty_formatting = pretty_formatting230 def get_name(self):231 return "json"232 def get_report_filename(self):233 return "report.js"234 def save_report(self, filename, report):235 save_report_into_file(236 report, filename,237 javascript_compatibility=self.javascript_compatibility, pretty_formatting=self.pretty_formatting238 )239 def load_report(self, path):240 report = load_report_from_file(path)241 report.bind(self, path)...

Full Screen

Full Screen

test_report_reportportal.py

Source:test_report_reportportal.py Github

copy

Full Screen

1import re2import os.path as osp3import mimetypes4import pytest5from pytest_mock import mocker6from helpers.utils import env_vars7from helpers.runner import run_suite_classes8from helpers.reporttests import ReportingSessionTests9from lemoncheesecake.reporting.backends import ReportPortalBackend10from lemoncheesecake.reporting.report import Log, Check, Attachment, Url11from lemoncheesecake.exceptions import UserError12def _test_reporting_session(**vars):13 backend = ReportPortalBackend()14 with env_vars(**vars):15 return backend.create_reporting_session(None, None, None, None)16@pytest.fixture17def rp_mock(mocker):18 mocker.patch("reportportal_client.ReportPortalServiceAsync")19 return mocker20def substr(value):21 return re.compile(re.escape(value))22def convert_status(status):23 return "passed" if status == "passed" else "failed"24def make_tags_from_test_tree_node(node):25 return node.tags + \26 ["%s_%s" % (name, value) for name, value in node.properties.items()] + \27 [link[1] or link[0] for link in node.links]28def assert_rp_calls(actual_calls, expected_calls):29 pattern_type = type(re.compile(r"foo"))30 int_as_str_pattern = re.compile(r"^(\d+)$")31 for actual_call, expected_call in zip(actual_calls, expected_calls):32 actual_name, actual_args, actual_kwargs = actual_call33 expected_name, expected_args, expected_kwargs = expected_call34 # method name:35 assert actual_name == expected_name36 # args:37 if actual_name == "log":38 assert int_as_str_pattern.match(actual_args[0]) is not None39 actual_args = actual_args[1:]40 for actual_arg, expected_arg in zip(actual_args, expected_args):41 if type(expected_arg) is pattern_type:42 assert expected_arg.search(actual_arg) is not None43 else:44 assert actual_arg == expected_arg45 # kwargs:46 for name, value in expected_kwargs.items():47 assert actual_kwargs[name] == value48 if actual_name.startswith("start_"):49 assert int_as_str_pattern.match(actual_kwargs["start_time"]) is not None50 if actual_name.startswith("finish_"):51 assert int_as_str_pattern.match(actual_kwargs["end_time"]) is not None52 assert len(actual_calls) == len(expected_calls)53def steps_to_calls(steps):54 for step in steps:55 yield "log", (substr(step.description), 'INFO'), {}56 for log in step.get_logs():57 if isinstance(log, Log):58 yield "log", (log.message, log.level.upper()), {}59 if isinstance(log, Check):60 message = "%s => %s" % (log.description, "OK" if log.is_successful else "NOT OK")61 if log.details:62 message += "\nDetails: %s" % log.details63 level = "INFO" if log.is_successful else "ERROR"64 yield "log", (message, level), {}65 if isinstance(log, Url):66 yield "log", (substr(log.url), "INFO"), {}67 if isinstance(log, Attachment):68 with open(log.filename, "rb") as fh:69 attachment_content = fh.read()70 attachment_arg = {71 "name": osp.basename(log.filename),72 "data": attachment_content,73 "mime": mimetypes.guess_type(log.filename)[0] or "application/octet-stream"74 }75 yield "log", (log.description, "INFO"), {"attachment": attachment_arg}76def start_test_item(item_type, name, description, tags=None):77 kwargs = {"item_type": item_type, "name": name, "description": description}78 if tags is not None:79 kwargs["tags"] = tags80 return "start_test_item", (), kwargs81def finish_test_item(status):82 return "finish_test_item", (), {"status": status}83def _tests_to_rp_calls(tests):84 for test in tests:85 yield start_test_item("TEST", test.name, test.description, make_tags_from_test_tree_node(test))86 for call in steps_to_calls(test.get_steps()):87 yield call88 yield finish_test_item(test.status)89def suites_to_rp_calls(suites):90 for suite in suites:91 # START SUITE92 yield start_test_item("SUITE", suite.name, suite.description, make_tags_from_test_tree_node(suite))93 # SUITE SETUP94 if suite.suite_setup:95 yield start_test_item("BEFORE_CLASS", "suite_setup", "Suite Setup")96 for call in steps_to_calls(suite.suite_setup.get_steps()):97 yield call98 yield finish_test_item(suite.suite_setup.status)99 # TESTS100 for call in _tests_to_rp_calls(suite.get_tests()):101 yield call102 # SUB SUITES103 for call in suites_to_rp_calls(suite.get_suites()):104 yield call105 # SUITE TEARDOWN106 if suite.suite_teardown:107 yield start_test_item("AFTER_CLASS", "suite_teardown", "Suite Teardown")108 for call in steps_to_calls(suite.suite_teardown.get_steps()):109 yield call110 yield finish_test_item(suite.suite_teardown.status)111 # END SUITE112 yield finish_test_item("passed")113def report_to_rp_calls(report, launch_name="Test Run", launch_description=None):114 yield "start_launch", (), {"name": launch_name, "description": launch_description}115 if report.test_session_setup:116 yield start_test_item("SUITE", "session_setup", "Test Session Setup")117 yield start_test_item("BEFORE_CLASS", "session_setup", "Test Session Setup")118 for call in steps_to_calls(report.test_session_setup.get_steps()):119 yield call120 yield finish_test_item(report.test_session_setup.status)121 yield finish_test_item(report.test_session_setup.status)122 for call in suites_to_rp_calls(report.get_suites()):123 yield call124 if report.test_session_teardown:125 yield start_test_item("SUITE", "session_teardown", "Test Session Teardown")126 yield start_test_item("AFTER_CLASS", "session_teardown", "Test Session Teardown")127 for call in steps_to_calls(report.test_session_teardown.get_steps()):128 yield call129 yield finish_test_item(report.test_session_teardown.status)130 yield finish_test_item(report.test_session_teardown.status)131 yield "finish_launch", (), {}132 yield "terminate", (), {}133try:134 import reportportal_client135except ImportError:136 pass # reportportal_client is not installed (reportportal is an optional feature), skip tests137else:138 @pytest.mark.usefixtures("rp_mock")139 class TestReportPortalReporting(ReportingSessionTests):140 def do_test_reporting_session(self, suites, fixtures=(), report_saving_strategy=None, nb_threads=1):141 if type(suites) not in (list, tuple):142 suites = [suites]143 with env_vars(LCC_RP_URL="http://localhost", LCC_RP_AUTH_TOKEN="sometoken", LCC_RP_PROJECT="myproj"):144 report = run_suite_classes(145 suites, backends=[ReportPortalBackend()], fixtures=fixtures, tmpdir=".", nb_threads=nb_threads146 )147 assert_rp_calls(148 reportportal_client.ReportPortalServiceAsync.return_value.mock_calls,149 list(report_to_rp_calls(report))150 )151 def test_create_reporting_session_with_only_required_parameters():152 _test_reporting_session(153 LCC_RP_URL="http://localhost", LCC_RP_AUTH_TOKEN="sometoken",154 LCC_RP_PROJECT="myproj",155 LCC_RP_LAUNCH_NAME=None, LCC_RP_LAUNCH_DESCRIPTION=None156 )157 def test_create_reporting_session_with_all_parameters():158 _test_reporting_session(159 LCC_RP_URL="http://localhost", LCC_RP_AUTH_TOKEN="sometoken",160 LCC_RP_PROJECT="myproj",161 LCC_RP_LAUNCH_NAME="Run", LCC_RP_LAUNCH_DESCRIPTION="Run"162 )163 def test_create_reporting_session_without_parameters():164 with pytest.raises(UserError):165 _test_reporting_session(166 LCC_RP_URL=None, LCC_RP_AUTH_TOKEN=None,167 LCC_RP_PROJECT=None,168 LCC_RP_LAUNCH_NAME=None, LCC_RP_LAUNCH_DESCRIPTION=None...

Full Screen

Full Screen

replay.py

Source:replay.py Github

copy

Full Screen

...85 for suite in report.get_suites():86 _replay_suite_events(suite, eventmgr)87 if report.test_session_teardown:88 eventmgr.fire(events.TestSessionTeardownStartEvent(report.test_session_teardown.start_time))89 _replay_steps_events(ReportLocation.in_test_session_teardown(), report.test_session_teardown.get_steps(), eventmgr)90 if report.test_session_teardown.end_time:91 eventmgr.fire(events.TestSessionTeardownEndEvent(report.test_session_teardown.end_time))92 if report.end_time:...

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 Lemoncheesecake 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