/usr/lib/python3/dist-packages/behave/parser.py is in python3-behave 1.2.5-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 | # -*- coding: utf-8 -*-
from behave import model, i18n
from behave.textutil import text as _text
import six
DEFAULT_LANGUAGE = 'en'
def parse_file(filename, language=None):
with open(filename, 'rb') as f:
# file encoding is assumed to be utf8. Oh, yes.
data = f.read().decode('utf8')
return parse_feature(data, language, filename)
def parse_feature(data, language=None, filename=None):
# ALL data operated on by the parser MUST be unicode
assert isinstance(data, six.text_type)
try:
result = Parser(language).parse(data, filename)
except ParserError as e:
e.filename = filename
raise
return result
def parse_steps(text, language=None, filename=None):
"""
Parse a number of steps a multi-line text from a scenario.
Scenario line with title and keyword is not provided.
:param text: Multi-line text with steps to parse (as unicode).
:param language: i18n language identifier (optional).
:param filename: Filename (optional).
:return: Parsed steps (if successful).
"""
assert isinstance(text, six.text_type)
try:
result = Parser(language, variant='steps').parse_steps(text, filename)
except ParserError as e:
e.filename = filename
raise
return result
def parse_tags(text):
"""
Parse tags from text (one or more lines, as string).
:param text: Multi-line text with tags to parse (as unicode).
:return: List of tags (if successful).
"""
# assert isinstance(text, unicode)
if not text:
return []
return Parser().parse_tags(text)
class ParserError(Exception):
def __init__(self, message, line, filename=None, line_text=None):
if line:
message += ' at line %d' % line
if line_text:
message += ": '%s'" % line_text.strip()
super(ParserError, self).__init__(message)
self.line = line
self.line_text = line_text
self.filename = filename
def __str__(self):
arg0 = _text(self.args[0])
if self.filename:
filename = _text(self.filename)
return 'Failed to parse "%s": %s' % (filename, arg0)
else:
return 'Failed to parse <string>: %s' % arg0
if six.PY2:
__unicode__ = __str__
__str__ = lambda self: self.__unicode__().encode("utf-8")
class Parser(object):
# pylint: disable=W0201,R0902
# W0201 Attribute ... defined outside __init__() method => reset()
# R0902 Too many instance attributes (15/10)
def __init__(self, language=None, variant=None):
if not variant:
variant = 'feature'
self.language = language
self.variant = variant
self.reset()
def reset(self):
# This can probably go away.
if self.language:
self.keywords = i18n.languages[self.language]
else:
self.keywords = None
self.state = 'init'
self.line = 0
self.last_step = None
self.multiline_start = None
self.multiline_leading = None
self.multiline_terminator = None
self.filename = None
self.feature = None
self.statement = None
self.tags = []
self.lines = []
self.table = None
self.examples = None
def parse(self, data, filename=None):
self.reset()
self.filename = filename
for line in data.split('\n'):
self.line += 1
if not line.strip() and not self.state == 'multiline':
# -- SKIP EMPTY LINES, except in multiline string args.
continue
self.action(line)
if self.table:
self.action_table('')
feature = self.feature
if feature:
feature.parser = self
self.reset()
return feature
def _build_feature(self, keyword, line):
name = line[len(keyword) + 1:].strip()
self.feature = model.Feature(self.filename, self.line, keyword,
name, tags=self.tags)
# -- RESET STATE:
self.tags = []
def _build_background_statement(self, keyword, line):
if self.tags:
msg = 'Background supports no tags: @%s' % (' @'.join(self.tags))
raise ParserError(msg, self.line, self.filename, line)
name = line[len(keyword) + 1:].strip()
statement = model.Background(self.filename, self.line, keyword, name)
self.statement = statement
self.feature.background = self.statement
def _build_scenario_statement(self, keyword, line):
name = line[len(keyword) + 1:].strip()
self.statement = model.Scenario(self.filename, self.line,
keyword, name, tags=self.tags)
self.feature.add_scenario(self.statement)
# -- RESET STATE:
self.tags = []
def _build_scenario_outline_statement(self, keyword, line):
# pylint: disable=C0103
# C0103 Invalid name "build_scenario_outline_statement", too long.
name = line[len(keyword) + 1:].strip()
self.statement = model.ScenarioOutline(self.filename, self.line,
keyword, name, tags=self.tags)
self.feature.add_scenario(self.statement)
# -- RESET STATE:
self.tags = []
def _build_examples(self, keyword, line):
if not isinstance(self.statement, model.ScenarioOutline):
message = 'Examples must only appear inside scenario outline'
raise ParserError(message, self.line, self.filename, line)
name = line[len(keyword) + 1:].strip()
self.examples = model.Examples(self.filename, self.line,
keyword, name)
# pylint: disable=E1103
# E1103 Instance of 'Background' has no 'examples' member
# (but some types could not be inferred).
self.statement.examples.append(self.examples)
def diagnose_feature_usage_error(self):
if self.feature:
return "Multiple features in one file are not supported."
else:
return "Feature should not be used here."
def diagnose_background_usage_error(self):
if self.feature and self.feature.scenarios:
return "Background may not occur after Scenario/ScenarioOutline."
elif self.tags:
return "Background does not support tags."
else:
return "Background should not be used here."
def diagnose_scenario_usage_error(self):
if not self.feature:
return "Scenario may not occur before Feature."
else:
return "Scenario should not be used here."
def diagnose_scenario_outline_usage_error(self):
if not self.feature:
return "ScenarioOutline may not occur before Feature."
else:
return "ScenarioOutline should not be used here."
def ask_parse_failure_oracle(self, line):
"""
Try to find the failure reason when a parse failure occurs:
Oracle, oracle, ... what went wrong?
Zzzz
:param line: Text line where parse failure occured (as string).
:return: Reason (as string) if an explanation is found.
Otherwise, empty string or None.
"""
feature_kwd = self.match_keyword('feature', line)
if feature_kwd:
return self.diagnose_feature_usage_error()
background_kwd = self.match_keyword('background', line)
if background_kwd:
return self.diagnose_background_usage_error()
scenario_kwd = self.match_keyword('scenario', line)
if scenario_kwd:
return self.diagnose_scenario_usage_error()
scenario_outline_kwd = self.match_keyword('scenario_outline', line)
if scenario_outline_kwd:
return self.diagnose_scenario_outline_usage_error()
# -- OTHERWISE:
if self.variant == 'feature' and not self.feature:
return "No feature found."
# -- FINALLY: No glue what went wrong.
return None
def action(self, line):
if line.strip().startswith('#') and not self.state == 'multiline':
if self.keywords or self.state != 'init' or self.tags:
return
line = line.strip()[1:].strip()
if line.lstrip().lower().startswith('language:'):
language = line[9:].strip()
self.language = language
self.keywords = i18n.languages[language]
return
func = getattr(self, 'action_' + self.state, None)
if func is None:
line = line.strip()
msg = "Parser in unknown state %s;" % self.state
raise ParserError(msg, self.line, self.filename, line)
if not func(line):
line = line.strip()
msg = "\nParser failure in state %s, at line %d: '%s'\n" % \
(self.state, self.line, line)
reason = self.ask_parse_failure_oracle(line)
if reason:
msg += "REASON: %s" % reason
raise ParserError(msg, None, self.filename)
def action_init(self, line):
line = line.strip()
if line.startswith('@'):
self.tags.extend(self.parse_tags(line))
return True
feature_kwd = self.match_keyword('feature', line)
if feature_kwd:
self._build_feature(feature_kwd, line)
self.state = 'feature'
return True
return False
def subaction_detect_next_scenario(self, line):
if line.startswith('@'):
self.tags.extend(self.parse_tags(line))
self.state = 'next_scenario'
return True
scenario_kwd = self.match_keyword('scenario', line)
if scenario_kwd:
self._build_scenario_statement(scenario_kwd, line)
self.state = 'scenario'
return True
scenario_outline_kwd = self.match_keyword('scenario_outline', line)
if scenario_outline_kwd:
self._build_scenario_outline_statement(scenario_outline_kwd, line)
self.state = 'scenario'
return True
# -- OTHERWISE:
return False
def action_feature(self, line):
line = line.strip()
if self.subaction_detect_next_scenario(line):
return True
background_kwd = self.match_keyword('background', line)
if background_kwd:
self._build_background_statement(background_kwd, line)
self.state = 'steps'
return True
self.feature.description.append(line)
return True
def action_next_scenario(self, line):
"""
Entered after first tag for Scenario/ScenarioOutline is detected.
"""
line = line.strip()
if self.subaction_detect_next_scenario(line):
return True
return False
def action_scenario(self, line):
"""
Entered when Scenario/ScenarioOutline keyword/line is detected.
Hunts/collects scenario description lines.
DETECT:
* first step of Scenario/ScenarioOutline
* next Scenario/ScenarioOutline.
"""
line = line.strip()
step = self.parse_step(line)
if step:
# -- FIRST STEP DETECTED: End collection of scenario descriptions.
self.state = 'steps'
self.statement.steps.append(step)
return True
# -- CASE: Detect next Scenario/ScenarioOutline
# * Scenario with scenario description, but without steps.
# * Title-only scenario without scenario description and steps.
if self.subaction_detect_next_scenario(line):
return True
# -- OTHERWISE: Add scenario description line.
# pylint: disable=E1103
# E1103 Instance of 'Background' has no 'description' member...
self.statement.description.append(line)
return True
def action_steps(self, line):
"""
Entered when first step is detected (or nested step parsing).
Subcases:
* step
* multi-line text (doc-string), following a step
* table, following a step
* examples for a ScenarioOutline, after ScenarioOutline steps
DETECT:
* next Scenario/ScenarioOutline
"""
# pylint: disable=R0911
# R0911 Too many return statements (8/6)
stripped = line.lstrip()
if stripped.startswith('"""') or stripped.startswith("'''"):
self.state = 'multiline'
self.multiline_start = self.line
self.multiline_terminator = stripped[:3]
self.multiline_leading = line.index(stripped[0])
return True
line = line.strip()
step = self.parse_step(line)
if step:
self.statement.steps.append(step)
return True
if self.subaction_detect_next_scenario(line):
return True
examples_kwd = self.match_keyword('examples', line)
if examples_kwd:
self._build_examples(examples_kwd, line)
self.state = 'table'
return True
if line.startswith('|'):
assert self.statement.steps, "TABLE-START without step detected."
self.state = 'table'
return self.action_table(line)
return False
def action_multiline(self, line):
if line.strip().startswith(self.multiline_terminator):
step = self.statement.steps[-1]
step.text = model.Text('\n'.join(self.lines), 'text/plain',
self.multiline_start)
if step.name.endswith(':'):
step.name = step.name[:-1]
self.lines = []
self.multiline_terminator = None
self.state = 'steps'
return True
self.lines.append(line[self.multiline_leading:])
# -- BETTER DIAGNOSTICS: May remove non-whitespace in execute_steps()
removed_line_prefix = line[:self.multiline_leading]
if removed_line_prefix.strip():
message = "BAD-INDENT in multiline text: "
message += "Line '%s' would strip leading '%s'" % \
(line, removed_line_prefix)
raise ParserError(message, self.line, self.filename)
return True
def action_table(self, line):
line = line.strip()
if not line.startswith('|'):
if self.examples:
self.examples.table = self.table
self.examples = None
else:
step = self.statement.steps[-1]
step.table = self.table
if step.name.endswith(':'):
step.name = step.name[:-1]
self.table = None
self.state = 'steps'
return self.action_steps(line)
cells = [cell.strip() for cell in line.split('|')[1:-1]]
if self.table is None:
self.table = model.Table(cells, self.line)
else:
if len(cells) != len(self.table.headings):
raise ParserError("Malformed table", self.line)
self.table.add_row(cells, self.line)
return True
def match_keyword(self, keyword, line):
if not self.keywords:
self.language = DEFAULT_LANGUAGE
self.keywords = i18n.languages[DEFAULT_LANGUAGE]
for alias in self.keywords[keyword]:
if line.startswith(alias + ':'):
return alias
return False
def parse_tags(self, line):
'''
Parse a line with one or more tags:
* A tag starts with the AT sign.
* A tag consists of one word without whitespace chars.
* Multiple tags are separated with whitespace chars
* End-of-line comment is stripped.
:param line: Line with one/more tags to process.
:raise ParseError: If syntax error is detected.
'''
assert line.startswith('@')
tags = []
for word in line.split():
if word.startswith('@'):
tags.append(model.Tag(word[1:], self.line))
elif word.startswith('#'):
break # -- COMMENT: Skip rest of line.
else:
# -- BAD-TAG: Abort here.
raise ParserError("tag: %s (line: %s)" % (word, line),
self.line, self.filename)
return tags
def parse_step(self, line):
for step_type in ('given', 'when', 'then', 'and', 'but'):
for kw in self.keywords[step_type]:
if kw.endswith('<'):
whitespace = ''
kw = kw[:-1]
else:
whitespace = ' '
# try to match the keyword; also attempt a purely lowercase
# match if that'll work
if not (line.startswith(kw + whitespace)
or line.lower().startswith(kw.lower() + whitespace)):
continue
name = line[len(kw):].strip()
if step_type in ('and', 'but'):
if not self.last_step:
raise ParserError("No previous step", self.line)
step_type = self.last_step
else:
self.last_step = step_type
step = model.Step(self.filename, self.line, kw, step_type,
name)
return step
return None
def parse_steps(self, text, filename=None):
"""
Parse support for execute_steps() functionality that supports step with:
* multiline text
* table
:param text: Text that contains 0..* steps
:return: List of parsed steps (as model.Step objects).
"""
assert isinstance(text, six.text_type)
if not self.language:
self.language = "en"
self.reset()
self.filename = filename
self.statement = model.Scenario(filename, 0, "scenario", "")
self.state = 'steps'
for line in text.split("\n"):
self.line += 1
if not line.strip() and not self.state == 'multiline':
# -- SKIP EMPTY LINES, except in multiline string args.
continue
self.action(line)
# -- FINALLY:
if self.table:
self.action_table("")
steps = self.statement.steps
return steps
|