Best Python code snippet using lemoncheesecake
visualize_listener.py
Source:visualize_listener.py
1import os2import platform3import glob4import time5from robot.running.builder.parsers import RobotParser6from robot.running import EXECUTION_CONTEXTS7from robot.libraries.BuiltIn import BuiltIn8from fixture_parser import fixture9from gui_runner import gui_runner10from node import node11from node import rf12from win_renderer import win_renderer13from SeleniumLibrary import ElementFinder14# Time of render the element which current manipulating15render_delay = .26116# Keywords which should be ignored from rendering17ignore_render_keyword_list = []18# Keywords which don't need to be parse19bypass_build_keyword_list = []20class visualize_listener:21 ROBOT_LISTENER_API_VERSION = 222 def __init__(self):23 self.init_block()24 self.runner = gui_runner()25 self.platform = platform.system()26 self.execution_flow = []27 self.is_suite_teardown = False28 self.in_suite_teardown = False29 self.finder = ElementFinder.find30 self.is_render_on = False31 self.runner.run()32 while not self.runner.is_runner_ready:33 pass34 for i in range(len(ignore_render_keyword_list)):35 ignore_render_keyword_list[i] = ignore_render_keyword_list[i].lower()36 def start_suite(self, name, attr):37 self.current_file_path = attr['source']38 if os.path.isdir(attr['source']):39 self.block_folder_initer()40 elif os.path.isfile(attr['source']):41 self.block_suite()42 else:43 raise Exception("Fail to switch source.")44 def start_test(self, name, attr):45 self.testcase_name = attr['originalname']46 self.block_test()47 def start_keyword(self, name, attr):48 if fixture(attr['kwname'], []).is_fixture:49 return50 if EXECUTION_CONTEXTS.current.in_suite_teardown:51 if not self.in_suite_teardown:52 self.in_suite_teardown = True53 if not self.is_suite_teardown:54 self.runner.set_window_title("Suite Teardown")55 self.runner.set_node_list(self.suite_teardown.pop())56 else:57 self.runner.set_window_title("Suite Teardown (__init__)")58 self.runner.set_node_list(self.folder_initer_teardown.pop())59 self.execution_flow.append(attr['kwname'])60 if len(self.execution_flow) == 1:61 if self.runner.is_start_node:62 self.runner.is_start_node = False63 else:64 self.runner.next_node()65 else:66 self.runner.next_keyword(attr['kwname'], attr['args'])67 self.test_block()68 if self.runner.is_render_ready:69 if attr['kwname'].lower() in ignore_render_keyword_list:70 self.is_render_on = False71 ElementFinder.find = self.finder72 elif not self.is_render_on:73 self.is_render_on = True74 self.render()75 else:76 if self.is_render_on:77 self.is_render_on = False78 ElementFinder.find = self.finder79 def end_keyword(self, name, attr):80 if fixture(attr['kwname'], []).is_fixture:81 return82 if attr['status'] == "FAIL":83 self.runner.on_fail()84 elif attr['status'] == "PASS":85 self.runner.on_pass()86 self.execution_flow.pop(-1)87 def end_suite(self, name, attr):88 self.in_suite_teardown = False89 if not self.is_suite_teardown:90 self.is_suite_teardown = True91 else:92 if not self.folder_initer_teardown:93 self.runner.on_closing()94 def init_block(self):95 self.folder_initer_setup = []96 self.folder_initer_teardown = []97 self.suite_setup = []98 self.suite_teardown = []99 self.test_setup = []100 self.test_script = []101 self.test_teardown = []102 def block_folder_initer(self):103 self.runner.set_window_title("Suite Setup (__init__)")104 self.blocker(self.folder_initer_setup, self.folder_initer_teardown, isdir=True)105 def block_suite(self):106 self.runner.set_window_title("Suite Setup")107 self.blocker(self.suite_setup, self.suite_teardown, isdir=False)108 def block_test(self):109 self.runner.set_window_title("Test: {}".format(self.testcase_name))110 self.blocker(self.test_setup, self.test_teardown, isdir=False, script=self.test_script)111 def blocker(self, setup, teardown, isdir, script=None):112 if script is not None:113 def parse(keyword, resource, instance):114 node_list = []115 if fixture(keyword.name, []).is_fixture:116 kw_list, args_list = fixture(keyword.name, keyword.args).parse()117 for kw, args in zip(kw_list, args_list):118 node_list.append( node(kw, self.current_file_path, resource, args, keyword.type) )119 else:120 node_list.append( node(keyword.name, self.current_file_path, resource, keyword.args, keyword.type) )121 for n in node_list:122 n.build(bypass_build_keyword_list)123 instance.extend(node_list)124 self.test_setup.clear()125 self.test_teardown.clear()126 self.test_script.clear()127 rf.clear()128 suite = RobotParser().parse_suite_file(source=self.current_file_path)129 resource = []130 for imp in suite.resource.imports:131 if imp.type == "Resource":132 if os.path.isfile(os.path.join(os.path.dirname(suite.resource.source), imp.name)):133 resource.append(os.path.normpath(os.path.join(os.path.dirname(suite.resource.source), imp.name)))134 elif os.path.isfile(BuiltIn().replace_variables(imp.name)):135 resource.append(BuiltIn().replace_variables(imp.name))136 for test in suite.tests:137 if test.name == self.testcase_name:138 for keyword in test.keywords:139 if keyword.type == "setup":140 parse(keyword, resource, self.test_setup)141 elif keyword.type == "teardown":142 parse(keyword, resource, self.test_teardown)143 else:144 if keyword.type == "for":145 for for_item in keyword.keywords:146 parse(for_item, resource, self.test_script)147 else:148 parse(keyword, resource, self.test_script)149 self.runner.set_node_list(self.test_setup + self.test_script + self.test_teardown)150 else:151 def parse(source, setup, teardown):152 suite = RobotParser().parse_suite_file(source=source)153 resource = []154 for imp in suite.resource.imports:155 if imp.type == "Resource":156 if os.path.isfile(os.path.join(os.path.dirname(suite.resource.source), imp.name)):157 resource.append(os.path.normpath(os.path.join(os.path.dirname(suite.resource.source), imp.name)))158 elif os.path.isfile(BuiltIn().replace_variables(imp.name)):159 resource.append(BuiltIn().replace_variables(imp.name))160 for keyword in suite.keywords:161 node_list = []162 if fixture(keyword.name, keyword.args).is_fixture:163 kw_list, args_list = fixture(keyword.name, keyword.args).parse()164 for kw, args in zip(kw_list, args_list):165 node_list.append( node(kw, source, resource, args, keyword.type) )166 else:167 node_list.append( node(keyword.name, source, resource, keyword.args, keyword.type) )168 for n in node_list:169 n.build(bypass_build_keyword_list)170 if keyword.type == "setup":171 setup.extend(node_list)172 elif keyword.type == "teardown":173 teardown.append(node_list)174 else:175 raise Exception("Parse suite fail.")176 self.folder_initer_setup.clear()177 rf.clear()178 if isdir:179 if os.path.exists(self.current_file_path + "/__init__.robot"):180 parse(self.current_file_path + "/__init__.robot", self.folder_initer_setup, self.folder_initer_teardown)181 self.runner.set_node_list(self.folder_initer_setup)182 else:183 parse(self.current_file_path, self.suite_setup, self.suite_teardown)184 self.runner.set_node_list(self.suite_setup)185 def test_block(self):186 if self.runner.is_pause_ready:187 self.runner.can_step = True188 while self.runner.is_pause_ready:189 pass190 if self.runner.is_script_select or self.runner.is_keyword_tree_select:191 self.runner.clear_selection()192 def render(self):193 def wrapping(func):194 def do(element, panel_height):195 if self.platform == 'Windows':196 rdr = win_renderer(element.location['x'], element.location['y'] + panel_height)197 rdr.render(element.size['width'], element.size['height'])198 start = time.time()199 while time.time() - start < render_delay:200 rdr.render(element.size['width'], element.size['height'])201 win_renderer(-1, -1).stop_render()202 def wrapper(*args, **kwargs):203 rs = func(*args, **kwargs)204 lib = BuiltIn().get_library_instance('SeleniumLibrary')205 panel_height = lib.driver.execute_script('return window.outerHeight - window.innerHeight;')206 if rs:207 if type(rs) == list:208 for r in rs:209 do(r, panel_height)210 else:211 do(rs, panel_height)212 return rs213 return wrapper...
context.py
Source:context.py
1# Copyright 2008-2015 Nokia Networks2# Copyright 2016- Robot Framework Foundation3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15from contextlib import contextmanager16from robot.errors import DataError17from robot.utils import unic18class ExecutionContexts(object):19 def __init__(self):20 self._contexts = []21 @property22 def current(self):23 return self._contexts[-1] if self._contexts else None24 @property25 def top(self):26 return self._contexts[0] if self._contexts else None27 def __iter__(self):28 return iter(self._contexts)29 @property30 def namespaces(self):31 return (context.namespace for context in self)32 def start_suite(self, suite, namespace, output, dry_run=False):33 ctx = _ExecutionContext(suite, namespace, output, dry_run)34 self._contexts.append(ctx)35 return ctx36 def end_suite(self):37 self._contexts.pop()38# This is ugly but currently needed e.g. by BuiltIn39EXECUTION_CONTEXTS = ExecutionContexts()40class _ExecutionContext(object):41 _started_keywords_threshold = 42 # Jython on Windows don't work with higher42 def __init__(self, suite, namespace, output, dry_run=False):43 self.suite = suite44 self.test = None45 self.timeouts = set()46 self.namespace = namespace47 self.output = output48 self.dry_run = dry_run49 self.in_suite_teardown = False50 self.in_test_teardown = False51 self.in_keyword_teardown = 052 self._started_keywords = 053 self.timeout_occurred = False54 @contextmanager55 def suite_teardown(self):56 self.in_suite_teardown = True57 try:58 yield59 finally:60 self.in_suite_teardown = False61 @contextmanager62 def test_teardown(self, test):63 self.variables.set_test('${TEST_STATUS}', test.status)64 self.variables.set_test('${TEST_MESSAGE}', test.message)65 self.in_test_teardown = True66 self._remove_timeout(test.timeout)67 try:68 yield69 finally:70 self.in_test_teardown = False71 @contextmanager72 def keyword_teardown(self, error):73 self.variables.set_keyword('${KEYWORD_STATUS}', 'FAIL' if error else 'PASS')74 self.variables.set_keyword('${KEYWORD_MESSAGE}', unic(error or ''))75 self.in_keyword_teardown += 176 try:77 yield78 finally:79 self.in_keyword_teardown -= 180 @property81 @contextmanager82 def user_keyword(self):83 self.namespace.start_user_keyword()84 try:85 yield86 finally:87 self.namespace.end_user_keyword()88 @contextmanager89 def timeout(self, timeout):90 self._add_timeout(timeout)91 try:92 yield93 finally:94 self._remove_timeout(timeout)95 @property96 def in_teardown(self):97 return bool(self.in_suite_teardown or98 self.in_test_teardown or99 self.in_keyword_teardown)100 @property101 def variables(self):102 return self.namespace.variables103 def end_suite(self, suite):104 for name in ['${PREV_TEST_NAME}',105 '${PREV_TEST_STATUS}',106 '${PREV_TEST_MESSAGE}']:107 self.variables.set_global(name, self.variables[name])108 self.output.end_suite(suite)109 self.namespace.end_suite()110 EXECUTION_CONTEXTS.end_suite()111 def set_suite_variables(self, suite):112 self.variables['${SUITE_NAME}'] = suite.longname113 self.variables['${SUITE_SOURCE}'] = suite.source or ''114 self.variables['${SUITE_DOCUMENTATION}'] = suite.doc115 self.variables['${SUITE_METADATA}'] = suite.metadata.copy()116 def report_suite_status(self, status, message):117 self.variables['${SUITE_STATUS}'] = status118 self.variables['${SUITE_MESSAGE}'] = message119 def start_test(self, test):120 self.test = test121 self._add_timeout(test.timeout)122 self.namespace.start_test()123 self.variables.set_test('${TEST_NAME}', test.name)124 self.variables.set_test('${TEST_DOCUMENTATION}', test.doc)125 self.variables.set_test('@{TEST_TAGS}', list(test.tags))126 def _add_timeout(self, timeout):127 if timeout:128 timeout.start()129 self.timeouts.add(timeout)130 def _remove_timeout(self, timeout):131 if timeout in self.timeouts:132 self.timeouts.remove(timeout)133 def end_test(self, test):134 self.test = None135 self._remove_timeout(test.timeout)136 self.namespace.end_test()137 self.variables.set_suite('${PREV_TEST_NAME}', test.name)138 self.variables.set_suite('${PREV_TEST_STATUS}', test.status)139 self.variables.set_suite('${PREV_TEST_MESSAGE}', test.message)140 self.timeout_occurred = False141 def start_keyword(self, keyword):142 self._started_keywords += 1143 if self._started_keywords > self._started_keywords_threshold:144 raise DataError('Maximum limit of started keywords exceeded.')145 self.output.start_keyword(keyword)146 def end_keyword(self, keyword):147 self.output.end_keyword(keyword)148 self._started_keywords -= 1149 def get_runner(self, name):150 return self.namespace.get_runner(name)151 def trace(self, message):152 self.output.trace(message)153 def debug(self, message):154 self.output.debug(message)155 def info(self, message):156 self.output.info(message)157 def warn(self, message):158 self.output.warn(message)159 def fail(self, message):...
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!!