Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change in gherkin reporting to support multiple spoken languages #343

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 43 additions & 24 deletions pytest_bdd/cucumber_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@
import sys
import time

from .feature import force_unicode
import six

from . import feature
from . import types

if six.PY3:
long = int


def add_options(parser):
Expand Down Expand Up @@ -72,10 +78,13 @@ def _get_result(self, step, report, error_message=False):
if report.passed or not step["failed"]: # ignore setup/teardown
result = {"status": "passed"}
elif report.failed and step["failed"]:
result = {"status": "failed", "error_message": force_unicode(report.longrepr) if error_message else ""}
result = {
"status": "failed",
"error_message": feature.force_unicode(report.longrepr) if error_message else "",
}
elif report.skipped:
result = {"status": "skipped"}
result["duration"] = int(math.floor((10 ** 9) * step["duration"])) # nanosec
result['duration'] = long(math.floor((10 ** 9) * step["duration"])) # nanosec
return result

def _serialize_tags(self, item):
Expand All @@ -90,11 +99,17 @@ def _serialize_tags(self, item):
}
]
"""
return [{"name": tag, "line": item["line_number"] - 1} for tag in item["tags"]]
return [
{
"name": tag,
"line": item["line_number"] - 1
}
for tag in item["tags"]
]

def _format_name(self, name, keys, values):
for param, value in zip(keys, values):
name = name.replace("<{}>".format(param), value)
name = name.replace('<{}>'.format(param), value)
return name

def _format_step_name(self, report, step):
Expand Down Expand Up @@ -122,8 +137,8 @@ def pytest_runtest_logreport(self, report):

def stepmap(step):
error_message = False
if step["failed"] and not scenario.setdefault("failed", False):
scenario["failed"] = True
if step['failed'] and not scenario.setdefault('failed', False):
scenario['failed'] = True
error_message = True

if self.expand:
Expand All @@ -135,37 +150,41 @@ def stepmap(step):
step_name = step["name"]

return {
"keyword": step["keyword"],
"keyword": step['keyword'],
"name": step_name,
"line": step["line_number"],
"match": {"location": ""},
"line": step['line_number'],
"match": {
"location": "",
},
"result": self._get_result(step, report, error_message),
}

feature_label = '{}'.format(feature.prefix_by_type(types.FEATURE)).split(":")[0]
scenario_label = '{}'.format(feature.prefix_by_type(types.SCENARIO)).split(":")[0]


if scenario["feature"]["filename"] not in self.features:
self.features[scenario["feature"]["filename"]] = {
"keyword": "Feature",
"keyword": feature_label,
"uri": scenario["feature"]["rel_filename"],
"name": scenario["feature"]["name"] or scenario["feature"]["rel_filename"],
"id": scenario["feature"]["rel_filename"].lower().replace(" ", "-"),
"line": scenario["feature"]["line_number"],
"line": scenario['feature']["line_number"],
"description": scenario["feature"]["description"],
"tags": self._serialize_tags(scenario["feature"]),
"elements": [],
}

self.features[scenario["feature"]["filename"]]["elements"].append(
{
"keyword": "Scenario",
"id": report.item["name"],
"name": scenario["name"],
"line": scenario["line_number"],
"description": "",
"tags": self._serialize_tags(scenario),
"type": "scenario",
"steps": [stepmap(step) for step in scenario["steps"]],
}
)
self.features[scenario["feature"]["filename"]]["elements"].append({
"keyword": scenario_label,
"id": report.item["name"],
"name": scenario["name"],
"line": scenario["line_number"],
"description": "",
"tags": self._serialize_tags(scenario),
"type": "scenario",
"steps": [stepmap(step) for step in scenario["steps"]],
})

def pytest_sessionstart(self):
self.suite_start_time = time.time()
Expand Down
120 changes: 55 additions & 65 deletions pytest_bdd/feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@
]

STEP_PARAM_RE = re.compile(r"\<(.+?)\>")
COMMENT_RE = re.compile(r"(^|(?<=\s))#")
SPLIT_LINE_RE = re.compile(r"(?<!\\)\|")
COMMENT_RE = re.compile(r'(^|(?<=\s))#')


def get_step_type(line):
Expand All @@ -83,7 +82,7 @@ def strip_comments(line):
"""
res = COMMENT_RE.search(line)
if res:
line = line[: res.start()]
line = line[:res.start()]
return line.strip()


Expand All @@ -96,7 +95,7 @@ def parse_line(line):
"""
for prefix, _ in STEP_PREFIXES:
if line.startswith(prefix):
return prefix.strip(), line[len(prefix) :].strip()
return prefix.strip(), line[len(prefix):].strip()
return "", line


Expand Down Expand Up @@ -137,19 +136,11 @@ def get_tags(line):

:return: List of tags.
"""
if not line or not line.strip().startswith("@"):
if not line or not line.strip().startswith('@'):
return set()
return set((tag.lstrip("@") for tag in line.strip().split(" @") if len(tag) > 1))


def split_line(line):
"""Split the given Examples line.

:param str|unicode line: Feature file Examples line.

:return: List of strings.
"""
return [cell.replace("\\|", "|").strip() for cell in SPLIT_LINE_RE.split(line[1:-1])]
return (
set((tag.lstrip('@') for tag in line.strip().split(' @') if len(tag) > 1))
)


def get_features(paths, **kwargs):
Expand All @@ -165,7 +156,12 @@ def get_features(paths, **kwargs):
if path not in seen_names:
seen_names.add(path)
if op.isdir(path):
features.extend(get_features(glob2.iglob(op.join(path, "**", "*.feature")), **kwargs))
features.extend(
get_features(
glob2.iglob(op.join(path, "**", "*.feature")),
**kwargs
)
)
else:
base, name = op.split(path)
feature = Feature.get_feature(base, name, **kwargs)
Expand Down Expand Up @@ -208,7 +204,9 @@ def add_example_row(self, param, values):
"""
if param in self.example_params:
raise exceptions.ExamplesNotValidError(
"""Example rows should contain unique parameters. "{0}" appeared more than once""".format(param)
"""Example rows should contain unique parameters. "{0}" appeared more than once""".format(
param,
)
)
self.example_params.append(param)
self.vertical_examples.append(values)
Expand All @@ -234,7 +232,7 @@ def get_params(self, converters, builtin=False):
raw_value = example[index]
if converters and param in converters:
value = converters[param](raw_value)
if not builtin or value.__class__.__module__ in {"__builtin__", "builtins"}:
if not builtin or value.__class__.__module__ in {'__builtin__', 'builtins'}:
example[index] = value
params.append(example)
return [self.example_params, params]
Expand Down Expand Up @@ -299,47 +297,31 @@ def __init__(self, basedir, filename, encoding="utf-8", strict_gherkin=True):

allowed_prev_mode = (types.BACKGROUND, types.GIVEN)
if not strict_gherkin:
allowed_prev_mode += (types.WHEN,)
allowed_prev_mode += (types.WHEN, )

if not scenario and prev_mode not in allowed_prev_mode and mode in types.STEP_TYPES:
raise exceptions.FeatureError(
"Step definition outside of a Scenario or a Background", line_number, clean_line, filename
)
"Step definition outside of a Scenario or a Background", line_number, clean_line, filename)

if strict_gherkin:
if (
self.background
and not scenario
and mode not in (types.SCENARIO, types.SCENARIO_OUTLINE, types.GIVEN, types.TAG)
):
if (self.background and not scenario and mode not in (
types.SCENARIO, types.SCENARIO_OUTLINE, types.GIVEN, types.TAG)):
raise exceptions.FeatureError(
"Background section can only contain Given steps", line_number, clean_line, filename
)
"Background section can only contain Given steps", line_number, clean_line, filename)

if mode == types.GIVEN and prev_mode not in (
types.GIVEN,
types.SCENARIO,
types.SCENARIO_OUTLINE,
types.BACKGROUND,
):
types.GIVEN, types.SCENARIO, types.SCENARIO_OUTLINE, types.BACKGROUND):
raise exceptions.FeatureError(
"Given steps must be the first within the Scenario", line_number, clean_line, filename
)
"Given steps must be the first within the Scenario", line_number, clean_line, filename)

if mode == types.WHEN and prev_mode not in (
types.SCENARIO,
types.SCENARIO_OUTLINE,
types.GIVEN,
types.WHEN,
):
types.SCENARIO, types.SCENARIO_OUTLINE, types.GIVEN, types.WHEN):
raise exceptions.FeatureError(
"When steps must be the first or follow Given steps", line_number, clean_line, filename
)
"When steps must be the first or follow Given steps", line_number, clean_line, filename)

if not self.background and mode == types.THEN and prev_mode not in types.STEP_TYPES:
raise exceptions.FeatureError(
"Then steps must follow Given or When steps", line_number, clean_line, filename
)
"Then steps must follow Given or When steps", line_number, clean_line, filename)

if mode == types.FEATURE:
if prev_mode is None or prev_mode == types.TAG:
Expand All @@ -351,10 +333,7 @@ def __init__(self, basedir, filename, encoding="utf-8", strict_gherkin=True):
else:
raise exceptions.FeatureError(
"Multiple features are not allowed in a single feature file",
line_number,
clean_line,
filename,
)
line_number, clean_line, filename)

prev_mode = mode

Expand All @@ -364,40 +343,42 @@ def __init__(self, basedir, filename, encoding="utf-8", strict_gherkin=True):
tags = get_tags(prev_line)
self.scenarios[parsed_line] = scenario = Scenario(self, parsed_line, line_number, tags=tags)
elif mode == types.BACKGROUND:
self.background = Background(feature=self, line_number=line_number)
self.background = Background(
feature=self,
line_number=line_number,
)
elif mode == types.EXAMPLES:
mode = types.EXAMPLES_HEADERS
(scenario or self).examples.line_number = line_number
elif mode == types.EXAMPLES_VERTICAL:
mode = types.EXAMPLE_LINE_VERTICAL
(scenario or self).examples.line_number = line_number
elif mode == types.EXAMPLES_HEADERS:
(scenario or self).examples.set_param_names([l for l in split_line(parsed_line) if l])
(scenario or self).examples.set_param_names(
[l.strip() for l in parsed_line.split("|")[1:-1] if l.strip()])
mode = types.EXAMPLE_LINE
elif mode == types.EXAMPLE_LINE:
(scenario or self).examples.add_example([l for l in split_line(stripped_line)])
(scenario or self).examples.add_example([l.strip() for l in stripped_line.split("|")[1:-1]])
elif mode == types.EXAMPLE_LINE_VERTICAL:
param_line_parts = [l for l in split_line(stripped_line)]
param_line_parts = [l.strip() for l in stripped_line.split("|")[1:-1]]
try:
(scenario or self).examples.add_example_row(param_line_parts[0], param_line_parts[1:])
except exceptions.ExamplesNotValidError as exc:
if scenario:
raise exceptions.FeatureError(
"""Scenario has not valid examples. {0}""".format(exc.args[0]),
line_number,
clean_line,
filename,
)
"""Scenario has not valid examples. {0}""".format(
exc.args[0]), line_number, clean_line, filename)
else:
raise exceptions.FeatureError(
"""Feature has not valid examples. {0}""".format(exc.args[0]),
line_number,
clean_line,
filename,
)
"""Feature has not valid examples. {0}""".format(
exc.args[0]), line_number, clean_line, filename)
elif mode and mode not in (types.FEATURE, types.TAG):
step = Step(
name=parsed_line, type=mode, indent=line_indent, line_number=line_number, keyword=keyword
name=parsed_line,
type=mode,
indent=line_indent,
line_number=line_number,
keyword=keyword,
)
if self.background and (mode == types.GIVEN or not strict_gherkin) and not scenario:
target = self.background
Expand Down Expand Up @@ -504,7 +485,7 @@ def validate(self):
raise exceptions.ScenarioExamplesNotValidError(
"""Scenario "{0}" in the feature "{1}" has not valid examples. """
"""Set of step parameters {2} should match set of example values {3}.""".format(
self.name, self.feature.filename, sorted(params), sorted(example_params)
self.name, self.feature.filename, sorted(params), sorted(example_params),
)
)

Expand Down Expand Up @@ -581,3 +562,12 @@ def add_step(self, step):
"""Add step to the background."""
step.background = self
self.steps.append(step)


def prefix_by_type(reqtype):

for prefix, _type in STEP_PREFIXES:
if _type==reqtype:
return prefix

return '<N/A type> {}'.format(reqtype)
Loading