diff --git a/getgauge/lsp_server.py b/getgauge/lsp_server.py index c900d43..20dcab1 100644 --- a/getgauge/lsp_server.py +++ b/getgauge/lsp_server.py @@ -1,15 +1,16 @@ import threading - from getgauge import processor, validator, refactor from getgauge.messages import lsp_pb2_grpc from getgauge.messages.lsp_pb2 import Empty -from getgauge.messages.messages_pb2 import Message, ImplementationFileGlobPatternResponse, StepNamesResponse, \ +from getgauge.messages.messages_pb2 import Message, \ + ImplementationFileGlobPatternResponse, StepNamesResponse, \ ImplementationFileListResponse from getgauge.registry import registry from getgauge.util import get_impl_files, get_step_impl_dir class LspServerHandler(lsp_pb2_grpc.lspServiceServicer): + def __init__(self, server): self.server = server self.kill_event = threading.Event() @@ -37,7 +38,8 @@ def GetImplementationFiles(self, request, context): def ImplementStub(self, request, context): res = Message() - processor.stub_impl_response(request.codes, request.implementationFilePath, res) + processor.stub_impl_response( + request.codes, request.implementationFilePath, res) return res.fileDiff def ValidateStep(self, request, context): diff --git a/getgauge/parser_parso.py b/getgauge/parser_parso.py index 76b9855..00775ce 100644 --- a/getgauge/parser_parso.py +++ b/getgauge/parser_parso.py @@ -10,25 +10,30 @@ class ParsoPythonFile(object): + @staticmethod def parse(file_path, content=None): """ - Create a PythonFile object with specified file_path and content. If content is None - then, it is loaded from the file_path method. Otherwise, file_path is only used for - reporting errors. + Create a PythonFile object with specified file_path and content. + If content is None then, it is loaded from the file_path method. + Otherwise, file_path is only used for reporting errors. """ try: - # Parso reads files in binary mode and converts to unicode using python_bytes_to_unicode() - # function. As a result, we no longer have information about original file encoding and - # output of module.get_content() can not be converted back to bytes. For now we can make a - # compromise by reading the file ourselves and passing content to parse() function. + # Parso reads files in binary mode and converts to unicode + # using python_bytes_to_unicode() function. As a result, + # we no longer have information about original file encoding and + # output of module.get_content() can't be converted back to bytes + # For now we can make a compromise by reading the file ourselves + # and passing content to parse() function. if content is None: with open(file_path) as f: content = f.read() - py_tree = _parser.parse(content, path=file_path, error_recovery=False) + py_tree = _parser.parse( + content, path=file_path, error_recovery=False) return ParsoPythonFile(file_path, py_tree) except parso.parser.ParserSyntaxError as ex: - logging.error("Failed to parse %s:%d '%s'", file_path, ex.error_leaf.line, ex.error_leaf.get_code()) + logging.error("Failed to parse %s:%d '%s'", file_path, + ex.error_leaf.line, ex.error_leaf.get_code()) def __init__(self, file_path, py_tree): self.file_path = file_path @@ -51,7 +56,10 @@ def _iter_step_func_decorators(self): break def _step_decorator_args(self, decorator): - """Get the arguments passed to step decorators converted to python objects""" + """ + Get the arguments passed to step decorators + converted to python objects. + """ args = decorator.children[3:-2] step = None if len(args) == 1: @@ -68,7 +76,7 @@ def _step_decorator_args(self, decorator): self.file_path, decorator.start_pos[0]) def iter_steps(self): - """Iterate over steps in the parsed file""" + """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: @@ -76,7 +84,7 @@ def iter_steps(self): yield step, func.name.value, span def _find_step_node(self, step_text): - """Find the ast node which contains the text""" + """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.children[3] @@ -97,7 +105,8 @@ def _create_param_node(self, parent, name, prefix, is_last): start_pos = parent[-1].end_pos[0], parent[-1].end_pos[1] + len(prefix) children = [parso.python.tree.Name(name, start_pos, prefix)] if not is_last: - children.append(parso.python.tree.Operator(',', children[-1].end_pos)) + children.append(parso.python.tree.Operator( + ',', children[-1].end_pos)) return parso.python.tree.Param(children, parent) def _move_param_nodes(self, param_nodes, move_param_from_idx): @@ -109,16 +118,19 @@ def _move_param_nodes(self, param_nodes, move_param_from_idx): return param_nodes # Get the prefix from second parameter to use with new parameters prefix = param_nodes[2].name.prefix if num_params > 1 else ' ' - new_param_nodes = [parso.python.tree.Operator('(', param_nodes[0].start_pos)] + new_param_nodes = [parso.python.tree.Operator( + '(', param_nodes[0].start_pos)] for i, move_from in enumerate(move_param_from_idx): param = self._create_param_node( new_param_nodes, - self._get_param_name(param_nodes, i) if move_from < 0 else param_nodes[move_from + 1].name.value, + self._get_param_name( + param_nodes, i) if move_from < 0 else param_nodes[move_from + 1].name.value, '' if i == 0 else prefix, i >= len(move_param_from_idx) - 1 ) new_param_nodes.append(param) - new_param_nodes.append(parso.python.tree.Operator(')', new_param_nodes[-1].end_pos)) + new_param_nodes.append(parso.python.tree.Operator( + ')', new_param_nodes[-1].end_pos)) # Change the parent to actual function for node in new_param_nodes: node.parent = param_nodes[0].parent @@ -126,9 +138,9 @@ def _move_param_nodes(self, param_nodes, move_param_from_idx): def refactor_step(self, old_text, new_text, move_param_from_idx): """ - Find the step with old_text and change it to new_text. The step function - parameters are also changed according to move_param_from_idx. Each entry in - this list should specify parameter position from old + Find the step with old_text and change it to new_text.The step function + parameters are also changed according to move_param_from_idx. + Each entry in this list should specify parameter position from old. """ diffs = [] step, func = self._find_step_node(old_text) @@ -137,7 +149,8 @@ def refactor_step(self, old_text, new_text, move_param_from_idx): step_diff = self._refactor_step_text(step, old_text, new_text) diffs.append(step_diff) params_list_node = func.children[2] - moved_params = self._move_param_nodes(params_list_node.children, move_param_from_idx) + moved_params = self._move_param_nodes( + params_list_node.children, move_param_from_idx) if params_list_node.children is not moved_params: # Record original parameter list span excluding braces params_span = self._span_from_pos( @@ -150,7 +163,7 @@ def refactor_step(self, old_text, new_text, move_param_from_idx): return diffs def get_code(self): - """Returns current content of the tree.""" + """Return current content of the tree.""" return self.py_tree.get_code() def _get_param_name(self, param_nodes, i): diff --git a/getgauge/parser_redbaron.py b/getgauge/parser_redbaron.py index 0836081..9d9f8fb 100644 --- a/getgauge/parser_redbaron.py +++ b/getgauge/parser_redbaron.py @@ -4,12 +4,13 @@ class RedbaronPythonFile(object): + @staticmethod def parse(file_path, content=None): """ - Create a PythonFile object with specified file_path and content. If content is None - then, it is loaded from the file_path method. Otherwise, file_path is only used for - reporting errors. + Create a PythonFile object with specified file_path and content. + If content is None then, it is loaded from the file_path method. + Otherwise, file_path is only used for reporting errors. """ try: if content is None: @@ -51,7 +52,7 @@ def calculate_span(): return calculate_span if lazy else calculate_span() def _iter_step_func_decorators(self): - """Find top level functions with step decorator in parsed file""" + """Find top level functions with step decorator in parsed file.""" for node in self.py_tree: if node.type == 'def': for decorator in node.decorators: @@ -60,7 +61,9 @@ def _iter_step_func_decorators(self): break def _step_decorator_args(self, decorator): - """Get the arguments passed to step decorators converted to python objects""" + """ + Get arguments passed to step decorators converted to python objects. + """ args = decorator.call.value step = None if len(args) == 1: @@ -70,21 +73,22 @@ def _step_decorator_args(self, decorator): pass if isinstance(step, six.string_types + (list,)): return step - logging.error("Decorator step accepts either a string or a list of strings - %s", + logging.error("Decorator step accepts either a string or a list of \ + strings - %s", self.file_path) else: logging.error("Decorator step accepts only one argument - %s", self.file_path) def iter_steps(self): - """Iterate over steps in the parsed file""" + """Iterate over steps in the parsed file.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) if step: yield step, func.name, self._span_for_node(func, True) def _find_step_node(self, step_text): - """Find the ast node which contains the text""" + """Find the ast node which contains the text.""" for func, decorator in self._iter_step_func_decorators(): step = self._step_decorator_args(decorator) arg_node = decorator.call.value[0].value @@ -121,9 +125,10 @@ def _move_params(self, params, move_param_from_idx): def refactor_step(self, old_text, new_text, move_param_from_idx): """ - Find the step with old_text and change it to new_text. The step function - parameters are also changed according to move_param_from_idx. Each entry in - this list should specify parameter position from old + Find the step with old_text and change it to new_text. + The step function parameters are also changed according + to move_param_from_idx. Each entry in this list should + specify parameter position from old """ diffs = [] step, func = self._find_step_node(old_text) @@ -139,5 +144,5 @@ def refactor_step(self, old_text, new_text, move_param_from_idx): return diffs def get_code(self): - """Returns current content of the tree.""" + """Return current content of the tree.""" return self.py_tree.dumps() diff --git a/getgauge/processor.py b/getgauge/processor.py index 67430c2..154a7e0 100644 --- a/getgauge/processor.py +++ b/getgauge/processor.py @@ -66,9 +66,11 @@ def _send_all_step_names(_request, response, _socket): def _execute_step(request, response, _socket): params = [] for p in request.executeStepRequest.parameters: - params.append(Table(p.table) if p.parameterType in [Parameter.Table, Parameter.Special_Table] else p.value) + params.append(Table(p.table) if p.parameterType in [ + Parameter.Table, Parameter.Special_Table] else p.value) set_response_values(request, response) - impl = registry.get_info_for(request.executeStepRequest.parsedStepText).impl + impl = registry.get_info_for( + request.executeStepRequest.parsedStepText).impl execute_method(params, impl, response, registry.is_continue_on_failure) @@ -82,70 +84,101 @@ def _execute_before_suite_hook(request, response, _socket, clear=True): registry.clear() load_impls(get_step_impl_dir()) if environ.get('DEBUGGING'): - ptvsd.enable_attach('', address=('127.0.0.1', int(environ.get('DEBUG_PORT')))) + ptvsd.enable_attach('', address=( + '127.0.0.1', int(environ.get('DEBUG_PORT')))) logging.info(ATTACH_DEBUGGER_EVENT) t = Timer(int(environ.get("debugger_wait_time", 30)), handle_detached) t.start() ptvsd.wait_for_attach() t.cancel() - execution_info = create_execution_context_from(request.executionStartingRequest.currentExecutionInfo) + execution_info = create_execution_context_from( + request.executionStartingRequest.currentExecutionInfo) run_hook(request, response, registry.before_suite(), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_after_suite_hook(request, response, _socket): - execution_info = create_execution_context_from(request.executionEndingRequest.currentExecutionInfo) + execution_info = create_execution_context_from( + request.executionEndingRequest.currentExecutionInfo) run_hook(request, response, registry.after_suite(), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_before_spec_hook(request, response, _socket): - execution_info = create_execution_context_from(request.specExecutionStartingRequest.currentExecutionInfo) - run_hook(request, response, registry.before_spec(execution_info.specification.tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + execution_info = create_execution_context_from( + request.specExecutionStartingRequest.currentExecutionInfo) + run_hook(request, response, registry.before_spec( + execution_info.specification.tags), execution_info) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_after_spec_hook(request, response, _socket): - execution_info = create_execution_context_from(request.specExecutionEndingRequest.currentExecutionInfo) - run_hook(request, response, registry.after_spec(execution_info.specification.tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + execution_info = create_execution_context_from( + request.specExecutionEndingRequest.currentExecutionInfo) + run_hook(request, response, registry.after_spec( + execution_info.specification.tags), execution_info) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_before_scenario_hook(request, response, _socket): - execution_info = create_execution_context_from(request.scenarioExecutionStartingRequest.currentExecutionInfo) - tags = list(execution_info.scenario.tags) + list(execution_info.specification.tags) + execution_info = create_execution_context_from( + request.scenarioExecutionStartingRequest.currentExecutionInfo) + tags = list(execution_info.scenario.tags) + \ + list(execution_info.specification.tags) run_hook(request, response, registry.before_scenario(tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_after_scenario_hook(request, response, _socket): - execution_info = create_execution_context_from(request.scenarioExecutionEndingRequest.currentExecutionInfo) - tags = list(execution_info.scenario.tags) + list(execution_info.specification.tags) + execution_info = create_execution_context_from( + request.scenarioExecutionEndingRequest.currentExecutionInfo) + tags = list(execution_info.scenario.tags) + \ + list(execution_info.specification.tags) run_hook(request, response, registry.after_scenario(tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_before_step_hook(request, response, _socket): - execution_info = create_execution_context_from(request.stepExecutionStartingRequest.currentExecutionInfo) - tags = list(execution_info.scenario.tags) + list(execution_info.specification.tags) + execution_info = create_execution_context_from( + request.stepExecutionStartingRequest.currentExecutionInfo) + tags = list(execution_info.scenario.tags) + \ + list(execution_info.specification.tags) run_hook(request, response, registry.before_step(tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _execute_after_step_hook(request, response, _socket): - execution_info = create_execution_context_from(request.stepExecutionEndingRequest.currentExecutionInfo) - tags = list(execution_info.scenario.tags) + list(execution_info.specification.tags) + execution_info = create_execution_context_from( + request.stepExecutionEndingRequest.currentExecutionInfo) + tags = list(execution_info.scenario.tags) + \ + list(execution_info.specification.tags) run_hook(request, response, registry.after_step(tags), execution_info) - response.executionStatusResponse.executionResult.message.extend(MessagesStore.pending_messages()) - response.executionStatusResponse.executionResult.screenshots.extend(ScreenshotsStore.pending_screenshots()) + response.executionStatusResponse.executionResult.message.extend( + MessagesStore.pending_messages()) + response.executionStatusResponse.executionResult.screenshots.extend( + ScreenshotsStore.pending_screenshots()) def _init_scenario_data_store(request, response, _socket): @@ -191,7 +224,8 @@ def _step_positions(request, response, _socket): def step_positions_response(file_path, response): positions = registry.get_step_positions(file_path) response.messageType = Message.StepPositionsResponse - response.stepPositionsResponse.stepPositions.extend([_create_pos(x) for x in positions]) + response.stepPositionsResponse.stepPositions.extend( + [_create_pos(x) for x in positions]) def _create_pos(p): @@ -206,7 +240,8 @@ def _kill_runner(_request, _response, socket): def _get_impl_file_list(_request, response, _socket): response.messageType = Message.ImplementationFileListResponse files = get_impl_files() - response.implementationFileListResponse.implementationFilePaths.extend(files) + response.implementationFileListResponse.implementationFilePaths.extend( + files) def _get_stub_impl_content(request, response, _socket): @@ -220,10 +255,13 @@ def stub_impl_response(codes, file_name, response): content = read_file_contents(file_name) prefix = "" if content is not None: - new_line_char = '\n' if len(content.strip().split('\n')) == len(content.split('\n')) else '' + new_line_char = '\n' if len(content.strip().split( + '\n')) == len(content.split('\n')) else '' last_line = len(content.split('\n')) - prefix = "from getgauge.python import step\n" if len(content.strip()) == 0 else new_line_char - span = Span(**{'start': last_line, 'startChar': 0, 'end': last_line, 'endChar': 0}) + prefix = "from getgauge.python import step\n" if len( + content.strip()) == 0 else new_line_char + span = Span(**{'start': last_line, 'startChar': 0, + 'end': last_line, 'endChar': 0}) else: file_name = get_file_name() prefix = "from getgauge.python import step\n" @@ -268,15 +306,16 @@ def dispatch_messages(socket): while True: request = read_message(socket, Message()) response = Message() - + try: processors[request.messageType](request, response, socket) except Exception as e: response = Message() response.messageType = Message.ExecutionStatusResponse response.executionStatusResponse.executionResult.failed = True - response.executionStatusResponse.executionResult.errorMessage = str(e) - response.executionStatusResponse.executionResult.stackTrace = traceback.format_exc() + response.executionStatusResponse.executionResult.errorMessage = str( + e) + response.executionStatusResponse.executionResult.stackTrace = traceback.format_exc() if request.messageType != Message.CacheFileRequest: send_message(response, request, socket) diff --git a/getgauge/python.py b/getgauge/python.py index cb6aed3..a785283 100644 --- a/getgauge/python.py +++ b/getgauge/python.py @@ -1,18 +1,18 @@ import sys import warnings - from getgauge.registry import registry, MessagesStore, ScreenshotsStore -try: +if sys.version_info[0] is 3: from collections.abc import MutableMapping -except ImportError: +else: from collections import MutableMapping def step(step_text): def _step(func): f_code = sys._getframe().f_back.f_code - span = {'start': f_code.co_firstlineno, 'startChar': 0, 'end': 0, 'endChar': 0} + span = {'start': f_code.co_firstlineno, + 'startChar': 0, 'end': 0, 'endChar': 0} registry.add_step(step_text, func, f_code.co_filename, span) return func @@ -169,8 +169,10 @@ def tags(self): def __str__(self): return "Specification: {{ name: {}, is_failing: {}, tags: {}, file_name: {} }}".format(self.name, - str(self.is_failing), - ", ".join(self.tags), + str( + self.is_failing), + ", ".join( + self.tags), self.file_name) def __eq__(self, other): @@ -245,7 +247,8 @@ def __getattr__(self, name): try: return self[name] except KeyError: - raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, name)) + raise AttributeError("'{0}' object has no attribute '{1}'".format( + self.__class__.__name__, name)) def __setattr__(self, name, value): self[name] = value @@ -254,7 +257,8 @@ def __delattr__(self, name): try: del self[name] except KeyError: - raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, name)) + raise AttributeError("'{0}' object has no attribute '{1}'".format( + self.__class__.__name__, name)) class DataStoreContainer(object): @@ -303,7 +307,8 @@ def __eq__(self, other): def _warn_datastore_deprecation(store_type): warnings.warn( - "'DataStoreFactory.{0}_data_store()' is deprecated in favour of 'data_store.{0}'".format(store_type), + "'DataStoreFactory.{0}_data_store()' is deprecated in favour of 'data_store.{0}'".format( + store_type), DeprecationWarning, stacklevel=3) warnings.simplefilter('default', DeprecationWarning) diff --git a/getgauge/registry.py b/getgauge/registry.py index c1393bb..731492f 100644 --- a/getgauge/registry.py +++ b/getgauge/registry.py @@ -78,7 +78,8 @@ def get(self, tags=None): return _filter_hooks(tags, getattr(self, '__{}'.format(hook))) def add(self, func, tags=None): - getattr(self, '__{}'.format(hook)).append({'tags': tags, 'func': func}) + getattr(self, '__{}'.format(hook)).append( + {'tags': tags, 'func': func}) setattr(self.__class__, hook, get) setattr(self.__class__, 'add_{}'.format(hook), add) @@ -87,7 +88,8 @@ def add(self, func, tags=None): def add_step(self, step_text, func, file_name, span=None, has_alias=False, aliases=None): if not isinstance(step_text, list): parsed_step_text = _get_step_value(step_text) - info = StepInfo(step_text, parsed_step_text, func, file_name, span, has_alias, aliases) + info = StepInfo(step_text, parsed_step_text, func, + file_name, span, has_alias, aliases) self.__steps_map.setdefault(parsed_step_text, []).append(info) return for text in step_text: @@ -128,7 +130,8 @@ def is_continue_on_failure(self, func, exception): def get_step_positions(self, file_name): positions = [] for step, infos in self.__steps_map.items(): - positions = positions + [{'stepValue': step, 'span': i.span} for i in infos if i.file_name == file_name] + positions = positions + [{'stepValue': step, 'span': i.span} + for i in infos if i.file_name == file_name] return positions def remove_steps(self, file_name): @@ -172,9 +175,11 @@ def _take_screenshot(): _file.close() return data except Exception as err: - logging.error("\nFailed to take screenshot using gauge_screenshot.\n{0}".format(err)) + logging.error( + "\nFailed to take screenshot using gauge_screenshot.\n{0}".format(err)) except: - logging.error("\nFailed to take screenshot using gauge_screenshot.\n{0}".format(sys.exc_info()[0])) + logging.error("\nFailed to take screenshot using gauge_screenshot.\n{0}".format( + sys.exc_info()[0])) return str.encode("") diff --git a/getgauge/static_loader.py b/getgauge/static_loader.py index b7a4c95..47bbfc8 100644 --- a/getgauge/static_loader.py +++ b/getgauge/static_loader.py @@ -5,7 +5,8 @@ def load_steps(python_file): for funcStep in python_file.iter_steps(): - registry.add_step(funcStep[0], funcStep[1], python_file.file_path, funcStep[2]) + registry.add_step(funcStep[0], funcStep[1], + python_file.file_path, funcStep[2]) def reload_steps(file_path, content=None): @@ -17,7 +18,8 @@ def reload_steps(file_path, content=None): def load_files(step_impl_dir): for dirpath, dirs, files in os.walk(step_impl_dir): - py_files = (os.path.join(dirpath, f) for f in files if f.endswith('.py')) + py_files = (os.path.join(dirpath, f) + for f in files if f.endswith('.py')) for file_path in py_files: pf = PythonFile.parse(file_path) if pf: diff --git a/getgauge/util.py b/getgauge/util.py index 5b44906..702fc92 100644 --- a/getgauge/util.py +++ b/getgauge/util.py @@ -21,7 +21,7 @@ def get_impl_files(): file_list = [] for root, _, files in os.walk(step_impl_dir): for file in files: - if file.endswith('.py') and '__init__.py' != os.path.basename(file) : + if file.endswith('.py') and '__init__.py' != os.path.basename(file): file_list.append(os.path.join(root, file)) return file_list diff --git a/getgauge/validator.py b/getgauge/validator.py index bdb9172..fe70acb 100644 --- a/getgauge/validator.py +++ b/getgauge/validator.py @@ -2,7 +2,6 @@ import random import re import string - from getgauge.messages.messages_pb2 import Message, StepValidateResponse from getgauge.registry import registry @@ -14,11 +13,13 @@ def validate_step(request, response): response.stepValidateResponse.errorType = StepValidateResponse.STEP_IMPLEMENTATION_NOT_FOUND response.stepValidateResponse.errorMessage = 'Step implementation not found' response.stepValidateResponse.isValid = False - response.stepValidateResponse.suggestion = _impl_suggestion(request.stepValue) + response.stepValidateResponse.suggestion = _impl_suggestion( + request.stepValue) elif registry.has_multiple_impls(request.stepText): response.stepValidateResponse.isValid = False response.stepValidateResponse.errorType = StepValidateResponse.DUPLICATE_STEP_IMPLEMENTATION - response.stepValidateResponse.suggestion = _duplicate_impl_suggestion(request) + response.stepValidateResponse.suggestion = _duplicate_impl_suggestion( + request) def _duplicate_impl_suggestion(request): @@ -29,7 +30,8 @@ def _duplicate_impl_suggestion(request): def _impl_suggestion(step_value): - name = re.sub('\s*\{\}\s*', ' ', step_value.stepValue).strip().replace(' ', '_').lower() + name = re.sub('\s*\{\}\s*', ' ', + step_value.stepValue).strip().replace(' ', '_').lower() return """@step("{}") def {}({}): assert False, "Add implementation code" @@ -43,7 +45,8 @@ def _format_params(params): def _format_impl(impl): - lines = [l for l in impl.split('\n') if l.strip().startswith('def') or l.strip().startswith('@')] + lines = [l for l in impl.split('\n') if l.strip( + ).startswith('def') or l.strip().startswith('@')] return '\n'.join(lines) + '\n ...\n' @@ -54,6 +57,5 @@ def _is_valid(name, template='{} = None'): except: return False - def _random_word(length=6): return ''.join(random.choice(string.ascii_lowercase) for _ in range(length)) diff --git a/requirements.txt b/requirements.txt index 9ca3555..881978d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,5 @@ ptvsd==3.0.0 grpcio-tools grpcio protobuf>=3.5.2 -parso \ No newline at end of file +parso +futures \ No newline at end of file diff --git a/skel/step_impl/step_impl.py b/skel/step_impl/step_impl.py index beba388..34ce8f9 100644 --- a/skel/step_impl/step_impl.py +++ b/skel/step_impl/step_impl.py @@ -24,8 +24,10 @@ def assert_default_vowels(given_vowels): @step("Almost all words have vowels ") def assert_words_vowel_count(table): - actual = [str(number_of_vowels(word)) for word in table.get_column_values_with_name("Word")] - expected = [str(count) for count in table.get_column_values_with_name("Vowel Count")] + actual = [str(number_of_vowels(word)) + for word in table.get_column_values_with_name("Word")] + expected = [str(count) + for count in table.get_column_values_with_name("Vowel Count")] assert expected == actual diff --git a/start.py b/start.py index 37e7d82..5787e75 100755 --- a/start.py +++ b/start.py @@ -3,12 +3,9 @@ import platform import sys import threading -from concurrent import futures +from concurrent.futures import ThreadPoolExecutor from os import path - - import grpc - from getgauge import connection, processor from getgauge import lsp_server from getgauge.impl_loader import copy_skel_files @@ -29,23 +26,26 @@ def main(): load_implementations() start() + def load_implementations(): d = get_step_impl_dir() if path.exists(d): load_files(d) else: - logging.error('can not load implementations from {}. {} does not exist.'.format(d, d)) + logging.error( + 'can not load implementations from {}. {} does not exist.'.format(d, d)) def start(): if os.getenv('GAUGE_LSP_GRPC'): - server = grpc.server(futures.ThreadPoolExecutor(max_workers=1)) + server = grpc.server(ThreadPoolExecutor(max_workers=1)) p = server.add_insecure_port('127.0.0.1:0') handler = lsp_server.LspServerHandler(server) lsp_pb2_grpc.add_lspServiceServicer_to_server(handler, server) logging.info('Listening on port:{}'.format(p)) server.start() - wait_thread = threading.Thread(name="listener", target=handler.wait_till_terminated) + wait_thread = threading.Thread( + name="listener", target=handler.wait_till_terminated) wait_thread.start() wait_thread.join() else: @@ -56,9 +56,11 @@ def start(): def _init_logger(): if os.getenv('IS_DAEMON'): f = '%(asctime)s.%(msecs)03d %(message)s' - logging.basicConfig(stream=sys.stdout, format=f, level=logging.DEBUG, datefmt='%H:%M:%S') + logging.basicConfig(stream=sys.stdout, format=f, + level=logging.DEBUG, datefmt='%H:%M:%S') else: - logging.basicConfig(stream=sys.stdout, format='%(message)s', level=logging.ERROR) + logging.basicConfig(stream=sys.stdout, + format='%(message)s', level=logging.ERROR) if __name__ == '__main__': diff --git a/tests/test_lsp_server.py b/tests/test_lsp_server.py index 409530d..78ab47c 100644 --- a/tests/test_lsp_server.py +++ b/tests/test_lsp_server.py @@ -39,7 +39,8 @@ def test_LspServerHandler_file_list(self): res = handler.GetImplementationFiles(req, None) - self.assertEqual(os.path.basename(res.implementationFilePaths[0]), 'foo.py') + self.assertEqual(os.path.basename( + res.implementationFilePaths[0]), 'foo.py') def test_LspServerHandler_step_names(self): handler = LspServerHandler(None) @@ -75,9 +76,11 @@ def test_LspServerHandler_validate_step(self): def foo(): pass ''') - step_value = ProtoStepValue(stepValue='foo', parameterizedStepValue='foo') + step_value = ProtoStepValue( + stepValue='foo', parameterizedStepValue='foo') - req = StepValidateRequest(stepText='foo', stepValue=step_value, numberOfParameters=0) + req = StepValidateRequest( + stepText='foo', stepValue=step_value, numberOfParameters=0) res = handler.ValidateStep(req, None) self.assertTrue(res.isValid) @@ -97,10 +100,13 @@ def test_LspServerHandler_implement_stub(self): handler = LspServerHandler(None) self.load_content_steps("@step('foo')\ndef foo():\n\tpass\n") - req = StubImplementationCodeRequest(implementationFilePath='New File', codes=['add hello']) + req = StubImplementationCodeRequest( + implementationFilePath='New File', codes=['add hello']) res = handler.ImplementStub(req, None) - self.assertEqual(os.path.basename(res.filePath), 'step_implementation.py') - self.assertEqual(res.textDiffs[0].content, 'from getgauge.python import step\n\nadd hello') + self.assertEqual(os.path.basename(res.filePath), + 'step_implementation.py') + self.assertEqual( + res.textDiffs[0].content, 'from getgauge.python import step\n\nadd hello') def test_LspServerHandler_refactor(self): handler = LspServerHandler(None) @@ -111,7 +117,8 @@ def test_LspServerHandler_refactor(self): def foo(vowels): print(vowels) ''') - self.fs.create_file(os.path.join(get_step_impl_dir(), 'foo.py'), contents=content) + self.fs.create_file(os.path.join( + get_step_impl_dir(), 'foo.py'), contents=content) loader.load_files(get_step_impl_dir()) request = RefactorRequest() @@ -134,7 +141,8 @@ def foo(vowels): self.assertTrue(res.success) diff_contents = [diff.content for diff in res.fileChanges[0].diffs] self.assertIn("vowels, arg1", diff_contents) - self.assertIn("'Vowels in English language is .'", diff_contents) + self.assertIn( + "'Vowels in English language is .'", diff_contents) def test_LspServerHandler_cache_file(self): handler = LspServerHandler(None) @@ -146,7 +154,8 @@ def foo(vowels): print(vowels) ''') - self.assertTrue(registry.is_implemented('Vowels in English language are {}.')) + self.assertTrue(registry.is_implemented( + 'Vowels in English language are {}.')) content = dedent('''\ from getgauge.python import step @@ -155,7 +164,8 @@ def foo(vowels): def foo(): pass ''') - req = CacheFileRequest(content=content, filePath='foo.py', status=CacheFileRequest.CHANGED) + req = CacheFileRequest( + content=content, filePath='foo.py', status=CacheFileRequest.CHANGED) handler.CacheFile(req, None) self.assertTrue(registry.is_implemented('get lost!')) diff --git a/tests/test_parser.py b/tests/test_parser.py index e556313..05050de 100644 --- a/tests/test_parser.py +++ b/tests/test_parser.py @@ -219,7 +219,8 @@ def print_hello(): self.assertEqual(diffs, [ (_span(1, 6, 1, 19), '"display hello"'), ]) - self.assertEqual(pf.get_code(), content.replace('print hello', 'display hello')) + self.assertEqual(pf.get_code(), content.replace( + 'print hello', 'display hello')) def test_refactor_step_only_step_text_in_list(self): content = dedent("""\ @@ -237,7 +238,8 @@ def print_word(word): self.assertEqual(diffs, [ (_span(3, 4, 3, 20), "'show '"), ]) - self.assertEqual(pf.get_code(), content.replace('display ', 'show ')) + self.assertEqual(pf.get_code(), content.replace( + 'display ', 'show ')) def test_refactor_step_add_arg_in_empty(self): content = dedent("""\ diff --git a/tests/test_processor.py b/tests/test_processor.py index 28f9eb8..81c0de0 100644 --- a/tests/test_processor.py +++ b/tests/test_processor.py @@ -2,9 +2,7 @@ from socket import socket, AF_INET, SOCK_STREAM from unittest import main from textwrap import dedent - from pyfakefs.fake_filesystem_unittest import TestCase - from getgauge import static_loader as loader from getgauge.messages.messages_pb2 import Message, StepValidateResponse, TextDiff, CacheFileRequest from getgauge.messages.spec_pb2 import ProtoExecutionResult, Parameter, Span @@ -64,8 +62,10 @@ def test_Processor_spec_data_store_init_request(self): processors[Message.SpecDataStoreInit](None, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) - self.assertEqual(0, response.executionStatusResponse.executionResult.executionTime) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + 0, response.executionStatusResponse.executionResult.executionTime) self.assertDictEqual({}, data_store.spec) @@ -78,8 +78,10 @@ def test_Processor_scenario_data_store_init_request(self): processors[Message.ScenarioDataStoreInit](None, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) - self.assertEqual(0, response.executionStatusResponse.executionResult.executionTime) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + 0, response.executionStatusResponse.executionResult.executionTime) self.assertDictEqual({}, data_store.scenario) @@ -91,11 +93,14 @@ def test_Processor_step_names_request(self): processors[Message.StepNamesRequest](None, response, None) self.assertEqual(Message.StepNamesResponse, response.messageType) - self.assertEqual({'Step with ', 'Step 4'}, set(response.stepNamesResponse.steps)) + self.assertEqual({'Step with ', 'Step 4'}, + set(response.stepNamesResponse.steps)) def test_Processor_step_name_request(self): - registry.add_step('Step with ', 'func', '', {'start': 1, 'startChar': 0, 'end': 3, 'endChar': 10}) - registry.add_step('Step 4', 'func1', '', {'start': 5, 'startChar': 0, 'end': 6, 'endChar': 10}) + registry.add_step('Step with ', 'func', '', { + 'start': 1, 'startChar': 0, 'end': 3, 'endChar': 10}) + registry.add_step('Step 4', 'func1', '', { + 'start': 5, 'startChar': 0, 'end': 6, 'endChar': 10}) response = Message() request = Message() request.stepNameRequest.stepValue = 'Step {} with {}' @@ -103,7 +108,8 @@ def test_Processor_step_name_request(self): processors[Message.StepNameRequest](request, response, None) self.assertEqual(Message.StepNameResponse, response.messageType) - self.assertEqual(['Step with '], response.stepNameResponse.stepName) + self.assertEqual(['Step with '], + response.stepNameResponse.stepName) self.assertEqual(True, response.stepNameResponse.isStepPresent) self.assertEqual(False, response.stepNameResponse.hasAlias) @@ -173,7 +179,8 @@ def test_Processor_invalid_step_validate_request_when_no_impl_found(self): self.assertEqual(Message.StepValidateResponse, response.messageType) self.assertFalse(response.stepValidateResponse.isValid) - self.assertEqual(StepValidateResponse.STEP_IMPLEMENTATION_NOT_FOUND, response.stepValidateResponse.errorType) + self.assertEqual(StepValidateResponse.STEP_IMPLEMENTATION_NOT_FOUND, + response.stepValidateResponse.errorType) self.assertTrue('@step("")\ndef step2():\n assert False, "Add implementation code"' in response.stepValidateResponse.suggestion) @@ -190,7 +197,8 @@ def test_Processor_invalid_step_validate_request_when_duplicate_impl_found(self) self.assertEqual(Message.StepValidateResponse, response.messageType) self.assertFalse(response.stepValidateResponse.isValid) - self.assertEqual(StepValidateResponse.DUPLICATE_STEP_IMPLEMENTATION, response.stepValidateResponse.errorType) + self.assertEqual(StepValidateResponse.DUPLICATE_STEP_IMPLEMENTATION, + response.stepValidateResponse.errorType) def test_Processor_execute_step_request(self): registry.add_step('Step 4', impl1, '') @@ -203,9 +211,12 @@ def test_Processor_execute_step_request(self): processors[Message.ExecuteStep](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) - self.assertEqual('', response.executionStatusResponse.executionResult.errorMessage) - self.assertEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + '', response.executionStatusResponse.executionResult.errorMessage) + self.assertEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_execute_step_request_with_param(self): registry.add_step('Step with ', impl, '') @@ -224,9 +235,12 @@ def test_Processor_execute_step_request_with_param(self): processors[Message.ExecuteStep](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) - self.assertEqual('', response.executionStatusResponse.executionResult.errorMessage) - self.assertEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + '', response.executionStatusResponse.executionResult.errorMessage) + self.assertEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failed_execute_step_request(self): response = Message() @@ -235,11 +249,16 @@ def test_Processor_failed_execute_step_request(self): processors[Message.ExecuteStep](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertNotEqual('', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) - self.assertEqual(False, response.executionStatusResponse.executionResult.recoverableError) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + False, response.executionStatusResponse.executionResult.recoverableError) def test_Processor_failed_execute_step_request_with_continue_on_failure(self): registry.add_step('Step 4', failing_impl, '') @@ -253,11 +272,16 @@ def test_Processor_failed_execute_step_request_with_continue_on_failure(self): processors[Message.ExecuteStep](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertNotEqual('', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) - self.assertEqual(True, response.executionStatusResponse.executionResult.recoverableError) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.recoverableError) def test_Processor_starting_execution_request(self): registry.add_before_suite(impl1) @@ -267,7 +291,8 @@ def test_Processor_starting_execution_request(self): processors[Message.ExecutionStarting](request, response, None, False) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_ending_execution_request(self): registry.add_after_suite(impl1) @@ -277,7 +302,8 @@ def test_Processor_ending_execution_request(self): processors[Message.ExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_spec_starting_execution_request(self): registry.add_before_spec(impl1) @@ -287,7 +313,8 @@ def test_Processor_spec_starting_execution_request(self): processors[Message.SpecExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_spec_ending_execution_request(self): registry.add_after_spec(impl1) @@ -297,7 +324,8 @@ def test_Processor_spec_ending_execution_request(self): processors[Message.SpecExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_scenario_starting_execution_request(self): registry.add_before_scenario(impl1) @@ -307,7 +335,8 @@ def test_Processor_scenario_starting_execution_request(self): processors[Message.ScenarioExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_scenario_ending_execution_request(self): registry.add_after_scenario(impl1) @@ -317,7 +346,8 @@ def test_Processor_scenario_ending_execution_request(self): processors[Message.ScenarioExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_step_starting_execution_request(self): registry.add_before_step(impl1) @@ -327,7 +357,8 @@ def test_Processor_step_starting_execution_request(self): processors[Message.StepExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_step_ending_execution_request(self): registry.add_after_step(impl1) @@ -337,7 +368,8 @@ def test_Processor_step_ending_execution_request(self): processors[Message.StepExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(False, response.executionStatusResponse.executionResult.failed) + self.assertEqual( + False, response.executionStatusResponse.executionResult.failed) def test_Processor_failing_starting_execution_request(self): registry.add_before_suite(failing_impl) @@ -346,10 +378,14 @@ def test_Processor_failing_starting_execution_request(self): processors[Message.ExecutionStarting](request, response, None, False) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_ending_execution_request(self): registry.add_after_suite(failing_impl) @@ -358,10 +394,14 @@ def test_Processor_failing_ending_execution_request(self): processors[Message.ExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_spec_starting_execution_request(self): registry.add_before_spec(failing_impl) @@ -370,10 +410,14 @@ def test_Processor_failing_spec_starting_execution_request(self): processors[Message.SpecExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_spec_ending_execution_request(self): registry.add_after_spec(failing_impl) @@ -382,10 +426,14 @@ def test_Processor_failing_spec_ending_execution_request(self): processors[Message.SpecExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_scenario_starting_execution_request(self): registry.add_before_scenario(failing_impl) @@ -394,10 +442,14 @@ def test_Processor_failing_scenario_starting_execution_request(self): processors[Message.ScenarioExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_scenario_ending_execution_request(self): registry.add_after_scenario(failing_impl) @@ -406,10 +458,14 @@ def test_Processor_failing_scenario_ending_execution_request(self): processors[Message.ScenarioExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_step_starting_execution_request(self): registry.add_before_step(failing_impl) @@ -418,10 +474,14 @@ def test_Processor_failing_step_starting_execution_request(self): processors[Message.StepExecutionStarting](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_failing_step_ending_execution_request(self): registry.add_after_step(failing_impl) @@ -430,10 +490,14 @@ def test_Processor_failing_step_ending_execution_request(self): processors[Message.StepExecutionEnding](request, response, None) self.assertEqual(Message.ExecutionStatusResponse, response.messageType) - self.assertEqual(True, response.executionStatusResponse.executionResult.failed) - self.assertEqual(ProtoExecutionResult.ASSERTION, response.executionStatusResponse.executionResult.errorType) - self.assertEqual('list index out of range', response.executionStatusResponse.executionResult.errorMessage) - self.assertNotEqual('', response.executionStatusResponse.executionResult.stackTrace) + self.assertEqual( + True, response.executionStatusResponse.executionResult.failed) + self.assertEqual(ProtoExecutionResult.ASSERTION, + response.executionStatusResponse.executionResult.errorType) + self.assertEqual('list index out of range', + response.executionStatusResponse.executionResult.errorMessage) + self.assertNotEqual( + '', response.executionStatusResponse.executionResult.stackTrace) def test_Processor_refactor_request_when_multiple_impl_found(self): registry.add_step('Step with ', 'func', '') @@ -453,7 +517,8 @@ def test_Processor_refactor_request_when_multiple_impl_found(self): def test_Processor_step_position_request(self): registry.add_step('Step with ', 'func', 'foo.py', {'start': 0, 'startChar': 0, 'end': 3, 'endChar': 10}) - registry.add_step('Step 1', 'func', 'foo.py', {'start': 4, 'startChar': 0, 'end': 7, 'endChar': 10}) + registry.add_step('Step 1', 'func', 'foo.py', { + 'start': 4, 'startChar': 0, 'end': 7, 'endChar': 10}) response = Message() request = Message() @@ -464,7 +529,8 @@ def test_Processor_step_position_request(self): self.assertEqual(Message.StepPositionsResponse, response.messageType) self.assertEqual('', response.refactorResponse.error) - steps = [(p.stepValue, p.span.start) for p in response.stepPositionsResponse.stepPositions] + steps = [(p.stepValue, p.span.start) + for p in response.stepPositionsResponse.stepPositions] self.assertIn(('Step {} with {}', 0), steps) self.assertIn(('Step 1', 4), steps) @@ -477,27 +543,33 @@ def test_Processor_put_stub_impl_request(self): request.stubImplementationCodeRequest.implementationFilePath = "" request.stubImplementationCodeRequest.codes.extend(codes) - processors[Message.StubImplementationCodeRequest](request, response, None) + processors[Message.StubImplementationCodeRequest]( + request, response, None) expected_output_codes = dedent('''\ from getgauge.python import step code1 code2''') - expected_span = Span(**{'start': 0, 'startChar': 0, 'end': 0, 'endChar': 0}) - expected_text_diff = TextDiff(**{'span': expected_span, 'content': expected_output_codes}) + expected_span = Span( + **{'start': 0, 'startChar': 0, 'end': 0, 'endChar': 0}) + expected_text_diff = TextDiff( + **{'span': expected_span, 'content': expected_output_codes}) self.assertEqual(len(response.fileDiff.textDiffs), 1) self.assertEqual(response.fileDiff.textDiffs[0], expected_text_diff) - self.assertEqual(path.basename(response.fileDiff.filePath), "step_implementation.py") + self.assertEqual(path.basename( + response.fileDiff.filePath), "step_implementation.py") def test_Processor_glob_pattern(self): request = Message() response = Message() - processors[Message.ImplementationFileGlobPatternRequest](request, response, None) + processors[Message.ImplementationFileGlobPatternRequest]( + request, response, None) - self.assertEqual(response.implementationFileGlobPatternResponse.globPatterns, ["step_impl/**/*.py"]) + self.assertEqual(response.implementationFileGlobPatternResponse.globPatterns, [ + "step_impl/**/*.py"]) def test_Processor_cache_file_with_opened_status(self): request = Message() diff --git a/tests/test_registry.py b/tests/test_registry.py index 946ac7a..99c0d64 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -48,7 +48,8 @@ def test_Registry_add_step_definition_with_parent_class_continue_on_failure(self RuntimeError())) def test_Registry_add_step_definition_with_alias(self): - registry.add_step(['Say to .', 'Tell to .'], 'impl', '') + registry.add_step(['Say to .', + 'Tell to .'], 'impl', '') info1 = registry.get_info_for('Say {} to {}.') info2 = registry.get_info_for('Tell {} to {}.') @@ -104,7 +105,8 @@ def test_Registry_get_multiple_impls(self): {'text': 'Step 1', 'func': 'func1', 'line': 3}] for info in infos: - registry.add_step(info['text'], info['func'], '', {'start': info['line']}) + registry.add_step(info['text'], info['func'], + '', {'start': info['line']}) parsed_step_text = re.sub('<[^<]+?>', '{}', infos[0]['text']) @@ -318,12 +320,15 @@ def test_Registry__step_positions_of_a_given_file(self): {'text': 'Step 1', 'func': 'func1', 'file_name': 'bar.py', 'span': {'start': 3}}] for info in infos: - registry.add_step(info['text'], info['func'], info['file_name'], info['span']) + registry.add_step(info['text'], info['func'], + info['file_name'], info['span']) positions = registry.get_step_positions('foo.py') - self.assertIn({'stepValue': 'Say {} to {}', 'span': {'start': 1}}, positions) - self.assertNotIn({'stepValue': 'Step 1', 'span': {'start': 3}}, positions) + self.assertIn({'stepValue': 'Say {} to {}', + 'span': {'start': 1}}, positions) + self.assertNotIn( + {'stepValue': 'Step 1', 'span': {'start': 3}}, positions) positions = registry.get_step_positions('bar.py')