| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
""" |
| 4 |
This module provides pre-/post-processors for the mod:`behave4cmd0.command_shell`. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import absolute_import, print_function |
| 8 |
import re |
| 9 |
import sys |
| 10 |
from six import string_types |
| 11 |
|
| 12 |
|
| 13 |
# ----------------------------------------------------------------------------- |
| 14 |
# UTILITY: |
| 15 |
# ----------------------------------------------------------------------------- |
| 16 |
def posixpath_normpath(filename): |
| 17 |
if not filename: |
| 18 |
return filename |
| 19 |
return filename.replace("\\", "/").replace("//", "/") |
| 20 |
|
| 21 |
|
| 22 |
# ----------------------------------------------------------------------------- |
| 23 |
# LINE PROCESSORS: |
| 24 |
# ----------------------------------------------------------------------------- |
| 25 |
class LineProcessor(object): |
| 26 |
"""Function-like object that may perform text-line transformations.""" |
| 27 |
def __init__(self, marker=None): |
| 28 |
self.marker = marker |
| 29 |
|
| 30 |
def reset(self): |
| 31 |
pass |
| 32 |
|
| 33 |
def __call__(self, text): |
| 34 |
return text |
| 35 |
|
| 36 |
|
| 37 |
class TracebackLineNormalizer(LineProcessor): |
| 38 |
"""Line processor that tries to normalize path lines in a traceback dump.""" |
| 39 |
marker = "Traceback (most recent call last):" |
| 40 |
file_pattern = re.compile(r'\s\s+File "(?P<path>.*)", line .*') |
| 41 |
|
| 42 |
def __init__(self): |
| 43 |
super(TracebackLineNormalizer, self).__init__(self.marker) |
| 44 |
self.traceback_section = False |
| 45 |
|
| 46 |
def reset(self): |
| 47 |
self.traceback_section = False |
| 48 |
|
| 49 |
def __call__(self, line): |
| 50 |
"""Process a line and optionally transform it. |
| 51 |
|
| 52 |
:param line: line to process (as text) |
| 53 |
:return: Same line or transformed/normalized line (as text). |
| 54 |
""" |
| 55 |
marker = self.marker |
| 56 |
stripped_line = line.strip() |
| 57 |
if marker == stripped_line: |
| 58 |
assert not self.traceback_section |
| 59 |
self.traceback_section = True |
| 60 |
# print("XXX: TRACEBACK-START") |
| 61 |
elif self.traceback_section: |
| 62 |
matched = self.file_pattern.match(line) |
| 63 |
if matched: |
| 64 |
# matched_range = matched.regs[1] |
| 65 |
filename = matched.groups()[0] |
| 66 |
new_filename = posixpath_normpath(filename) |
| 67 |
if new_filename != filename: |
| 68 |
# print("XXX: %r => %r" % (filename, new_filename)) |
| 69 |
line = line.replace(filename, new_filename) |
| 70 |
elif not stripped_line or line[0].isalpha(): |
| 71 |
# -- DETECTED TRCAEBACK-END: exception-description |
| 72 |
# print("XXX: TRACEBACK-END") |
| 73 |
self.traceback_section = False |
| 74 |
return line |
| 75 |
|
| 76 |
|
| 77 |
class ExceptionWithPathNormalizer(LineProcessor): |
| 78 |
"""Normalize filename path in Exception line (for Windows).""" |
| 79 |
# http://myregexp.com/examples.html |
| 80 |
# Windows File Name Regexp |
| 81 |
# (?i) ^ (?! ^ (PRN | AUX | CLOCK\$ | NUL | CON | COM\d | LPT\d |\..* )(\..+)?$) |
| 82 |
# [ ^\\\./:\ * \?\"<>\|][^\\/:\*\?\"<>\|]{0,254}$ |
| 83 |
problematic_path_patterns = [ |
| 84 |
'ConfigError: No steps directory in "(?P<path>.*)"', |
| 85 |
'ParserError: Failed to parse "(?P<path>.*)"', |
| 86 |
"Error: [Errno 2] No such file or directory: '(?P<path>.*)'", |
| 87 |
] |
| 88 |
|
| 89 |
def __init__(self, pattern, marker_text=None): |
| 90 |
super(ExceptionWithPathNormalizer, self).__init__(marker_text) |
| 91 |
self.pattern = re.compile(pattern, re.UNICODE) |
| 92 |
self.marker = marker_text |
| 93 |
|
| 94 |
def __call__(self, line): |
| 95 |
matched = self.pattern.search(line) |
| 96 |
if matched: |
| 97 |
# -- ONLY: One pattern per line should match. |
| 98 |
filename = matched.groupdict()["path"] |
| 99 |
new_filename = posixpath_normpath(filename) |
| 100 |
if new_filename != filename: |
| 101 |
line = line.replace(filename, new_filename) |
| 102 |
return line |
| 103 |
|
| 104 |
|
| 105 |
# ----------------------------------------------------------------------------- |
| 106 |
# COMMAND OUTPUT PROCESSORS: |
| 107 |
# ----------------------------------------------------------------------------- |
| 108 |
class CommandPostProcessor(object): |
| 109 |
"""Syntactic sugar to mark a command post-processor.""" |
| 110 |
|
| 111 |
|
| 112 |
class CommandOutputProcessor(CommandPostProcessor): |
| 113 |
"""Abstract base class functionality for a CommandPostProcessor that |
| 114 |
post-processes the output of a command. |
| 115 |
""" |
| 116 |
enabled = True |
| 117 |
output_parts = ("stderr", "stdout") |
| 118 |
|
| 119 |
def __init__(self, enabled=None, output_parts=None): |
| 120 |
if enabled is None: |
| 121 |
# -- AUTO-DETECT: Enabled on Windows platform |
| 122 |
enabled = self.__class__.enabled |
| 123 |
if output_parts is None: |
| 124 |
output_parts = self.__class__.output_parts |
| 125 |
self.enabled = enabled |
| 126 |
self.output_parts = output_parts |
| 127 |
|
| 128 |
def matches_output(self, text): |
| 129 |
"""Abstract method that should be overwritten.""" |
| 130 |
# pylint: disable=no-self-use, unused-argument |
| 131 |
return False |
| 132 |
|
| 133 |
def process_output(self, text): # pylint: disable=no-self-use |
| 134 |
"""Abstract method that should be overwritten.""" |
| 135 |
changed = False |
| 136 |
return changed, text |
| 137 |
|
| 138 |
def __call__(self, command_result): |
| 139 |
"""Core functionality of command output processor. |
| 140 |
|
| 141 |
:param command_result: As value object w/ command execution details. |
| 142 |
:return: Command result |
| 143 |
""" |
| 144 |
if not self.enabled: |
| 145 |
return command_result |
| 146 |
|
| 147 |
changes = 0 |
| 148 |
for output_name in self.output_parts: |
| 149 |
output = getattr(command_result, output_name) |
| 150 |
if output and self.matches_output(output): |
| 151 |
changed, new_output = self.process_output(output) |
| 152 |
if changed: |
| 153 |
changes += 1 |
| 154 |
setattr(command_result, output_name, new_output) |
| 155 |
|
| 156 |
if changes: |
| 157 |
# -- RESET: Composite output |
| 158 |
# pylint: disable=protected-access |
| 159 |
command_result._output = None |
| 160 |
return command_result |
| 161 |
|
| 162 |
|
| 163 |
class LineCommandOutputProcessor(CommandOutputProcessor): |
| 164 |
"""Provides functionality to process text in line-oriented way by using |
| 165 |
a number of line processors. The line processors perform the actual work |
| 166 |
for transforming/normalizing the text. |
| 167 |
""" |
| 168 |
enabled = True |
| 169 |
line_processors = [TracebackLineNormalizer()] |
| 170 |
|
| 171 |
def __init__(self, line_processors=None): |
| 172 |
if line_processors is None: |
| 173 |
line_processors = self.__class__.line_processors |
| 174 |
super(LineCommandOutputProcessor, self).__init__(self.enabled) |
| 175 |
self.line_processors = line_processors |
| 176 |
self.markers = [p.marker for p in self.line_processors if p.marker] |
| 177 |
|
| 178 |
def matches_output(self, text): |
| 179 |
"""Indicates it text contains sections of interest. |
| 180 |
:param text: Text to inspect (as string). |
| 181 |
:return: True, if text contains Traceback sections. False, otherwise. |
| 182 |
""" |
| 183 |
if self.markers: |
| 184 |
for marker in self.markers: |
| 185 |
if marker in text: |
| 186 |
return True |
| 187 |
# -- OTHERWISE: |
| 188 |
return False |
| 189 |
|
| 190 |
def process_output(self, text): |
| 191 |
"""Normalizes multi-line text by applying the line processors. |
| 192 |
|
| 193 |
:param text: Text to process (as string). |
| 194 |
:return: Tuple (changed : bool, new_text : string) |
| 195 |
""" |
| 196 |
new_lines = [] |
| 197 |
changed = False |
| 198 |
for line_processor in self.line_processors: |
| 199 |
line_processor.reset() |
| 200 |
|
| 201 |
for line in text.splitlines(): |
| 202 |
# -- LINE PROCESSING PIPELINE: |
| 203 |
original_line = line |
| 204 |
for line_processor in self.line_processors: |
| 205 |
line = line_processor(line) |
| 206 |
|
| 207 |
if line != original_line: |
| 208 |
changed = True |
| 209 |
new_lines.append(line) |
| 210 |
|
| 211 |
if changed: |
| 212 |
text = "\n".join(new_lines) + "\n" |
| 213 |
return changed, text |
| 214 |
|
| 215 |
class TextProcessor(CommandOutputProcessor): |
| 216 |
"""Provides an adapter that uses an :class:`CommandOutputProcessor` |
| 217 |
as text processor (normalizer). |
| 218 |
""" |
| 219 |
|
| 220 |
def __init__(self, command_output_processor): |
| 221 |
self.command_output_processor = command_output_processor |
| 222 |
self.enabled = self.command_output_processor.enabled |
| 223 |
self.output_parts = self.command_output_processor.output_parts |
| 224 |
|
| 225 |
def process_output(self, text): |
| 226 |
return self.command_output_processor.process_output(text) |
| 227 |
|
| 228 |
def __call__(self, command_result): |
| 229 |
if isinstance(command_result, string_types): |
| 230 |
text = command_result |
| 231 |
return self.command_output_processor.process_output(text)[1] |
| 232 |
else: |
| 233 |
return self.command_output_processor(command_result) |
| 234 |
|
| 235 |
|
| 236 |
class BehaveWinCommandOutputProcessor(LineCommandOutputProcessor): |
| 237 |
"""Command output post-processor for :mod:`behave` on Windows platform. |
| 238 |
Mostly, normalizes windows paths in output and exceptions to conform to |
| 239 |
POSIX path conventions. |
| 240 |
""" |
| 241 |
enabled = sys.platform.startswith("win") or True |
| 242 |
line_processors = [ |
| 243 |
TracebackLineNormalizer(), |
| 244 |
ExceptionWithPathNormalizer( |
| 245 |
"ConfigError: No steps directory in '(?P<path>.*)'", |
| 246 |
"ConfigError: No steps directory in"), |
| 247 |
ExceptionWithPathNormalizer( |
| 248 |
'ParserError: Failed to parse "(?P<path>.*)"', |
| 249 |
"ParserError: Failed to parse"), |
| 250 |
ExceptionWithPathNormalizer( |
| 251 |
"No such file or directory: '(?P<path>.*)'", |
| 252 |
"[Errno 2] No such file or directory:"), # IOError |
| 253 |
ExceptionWithPathNormalizer( |
| 254 |
'^\s*File "(?P<path>.*)", line \d+, in ', |
| 255 |
'File "'), |
| 256 |
] |