Skip to content

Commit

Permalink
'Refactored by Sourcery'
Browse files Browse the repository at this point in the history
  • Loading branch information
Sourcery AI committed Nov 12, 2023
1 parent b901519 commit 3df6735
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 73 deletions.
2 changes: 1 addition & 1 deletion src/pytest_bdd/cucumber_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _get_result(self, step: dict[str, Any], report: TestReport, error_message: b
result: dict[str, Any] = {}
if report.passed or not step["failed"]: # ignore setup/teardown
result = {"status": "passed"}
elif report.failed and step["failed"]:
elif report.failed:
result = {"status": "failed", "error_message": str(report.longrepr) if error_message else ""}
elif report.skipped:
result = {"status": "skipped"}
Expand Down
10 changes: 3 additions & 7 deletions src/pytest_bdd/generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,7 @@ def add_options(parser: Parser) -> None:

def cmdline_main(config: Config) -> int | None:
"""Check config option to show missing code."""
if config.option.generate_missing:
return show_missing_code(config)
return None # Make mypy happy
return show_missing_code(config) if config.option.generate_missing else None


def generate_code(features: list[Feature], scenarios: list[ScenarioTemplate], steps: list[Step]) -> str:
Expand Down Expand Up @@ -179,13 +177,11 @@ def _show_missing_code_main(config: Config, session: Session) -> None:
features, scenarios, steps = parse_feature_files(config.option.features)

for item in session.items:
scenario = getattr(item.obj, "__scenario__", None)
if scenario:
if scenario := getattr(item.obj, "__scenario__", None):
if scenario in scenarios:
scenarios.remove(scenario)
for step in scenario.steps:
fixturedefs = _find_step_fixturedef(fm, item, step=step)
if fixturedefs:
if fixturedefs := _find_step_fixturedef(fm, item, step=step):
try:
steps.remove(step)
except ValueError:
Expand Down
74 changes: 39 additions & 35 deletions src/pytest_bdd/gherkin_terminal_reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,45 +58,49 @@ def pytest_runtest_logreport(self, report: TestReport) -> Any:

if isinstance(word, tuple):
word, word_markup = word
else:
if rep.passed:
word_markup = {"green": True}
elif rep.failed:
word_markup = {"red": True}
elif rep.skipped:
word_markup = {"yellow": True}
elif rep.passed:
word_markup = {"green": True}
elif rep.failed:
word_markup = {"red": True}
elif rep.skipped:
word_markup = {"yellow": True}

Check warning on line 66 in src/pytest_bdd/gherkin_terminal_reporter.py

View check run for this annotation

Codecov / codecov/patch

src/pytest_bdd/gherkin_terminal_reporter.py#L66

Added line #L66 was not covered by tests
feature_markup = {"blue": True}
scenario_markup = word_markup

if self.verbosity <= 0:
if (
self.verbosity > 0
and self.verbosity == 1
and hasattr(report, "scenario")
):
self.ensure_newline()
self._tw.write("Feature: ", **feature_markup)
self._tw.write(report.scenario["feature"]["name"], **feature_markup)
self._tw.write("\n")
self._tw.write(" Scenario: ", **scenario_markup)
self._tw.write(report.scenario["name"], **scenario_markup)
self._tw.write(" ")
self._tw.write(word, **word_markup)
self._tw.write("\n")
elif (
self.verbosity > 0
and self.verbosity == 1
or self.verbosity > 0
and self.verbosity > 1
and not hasattr(report, "scenario")
or self.verbosity <= 0
):
return super().pytest_runtest_logreport(rep)
elif self.verbosity == 1:
if hasattr(report, "scenario"):
self.ensure_newline()
self._tw.write("Feature: ", **feature_markup)
self._tw.write(report.scenario["feature"]["name"], **feature_markup)
self._tw.write("\n")
self._tw.write(" Scenario: ", **scenario_markup)
self._tw.write(report.scenario["name"], **scenario_markup)
self._tw.write(" ")
self._tw.write(word, **word_markup)
self._tw.write("\n")
else:
return super().pytest_runtest_logreport(rep)
elif self.verbosity > 1:
if hasattr(report, "scenario"):
self.ensure_newline()
self._tw.write("Feature: ", **feature_markup)
self._tw.write(report.scenario["feature"]["name"], **feature_markup)
self._tw.write("\n")
self._tw.write(" Scenario: ", **scenario_markup)
self._tw.write(report.scenario["name"], **scenario_markup)
self._tw.write("\n")
for step in report.scenario["steps"]:
self._tw.write(f" {step['keyword']} {step['name']}\n", **scenario_markup)
self._tw.write(" " + word, **word_markup)
self._tw.write("\n\n")
else:
return super().pytest_runtest_logreport(rep)
self.ensure_newline()
self._tw.write("Feature: ", **feature_markup)
self._tw.write(report.scenario["feature"]["name"], **feature_markup)
self._tw.write("\n")
self._tw.write(" Scenario: ", **scenario_markup)
self._tw.write(report.scenario["name"], **scenario_markup)
self._tw.write("\n")
for step in report.scenario["steps"]:
self._tw.write(f" {step['keyword']} {step['name']}\n", **scenario_markup)
self._tw.write(f" {word}", **word_markup)
self._tw.write("\n\n")
self.stats.setdefault(cat, []).append(rep)
return None
25 changes: 14 additions & 11 deletions src/pytest_bdd/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,14 @@ def parse_line(line: str) -> tuple[str, str]:
:return: `tuple` in form ("<prefix>", "<Line without the prefix>").
"""
for prefix, _ in STEP_PREFIXES:
if line.startswith(prefix):
return prefix.strip(), line[len(prefix) :].strip()
return "", line
return next(
(
(prefix.strip(), line[len(prefix) :].strip())
for prefix, _ in STEP_PREFIXES
if line.startswith(prefix)
),
("", line),
)


def strip_comments(line: str) -> str:
Expand All @@ -65,8 +69,7 @@ def strip_comments(line: str) -> str:
:return: Stripped line.
"""
res = COMMENT_RE.search(line)
if res:
if res := COMMENT_RE.search(line):
line = line[: res.start()]
return line.strip()

Expand All @@ -78,10 +81,10 @@ def get_step_type(line: str) -> str | None:
:return: SCENARIO, GIVEN, WHEN, THEN, or `None` if can't be detected.
"""
for prefix, _type in STEP_PREFIXES:
if line.startswith(prefix):
return _type
return None
return next(
(_type for prefix, _type in STEP_PREFIXES if line.startswith(prefix)),
None,
)


def parse_feature(basedir: str, filename: str, encoding: str = "utf-8") -> Feature:
Expand Down Expand Up @@ -189,7 +192,7 @@ def parse_feature(basedir: str, filename: str, encoding: str = "utf-8") -> Featu
scenario.examples.set_param_names([l for l in split_line(parsed_line) if l])
mode = types.EXAMPLE_LINE
elif mode == types.EXAMPLE_LINE:
scenario.examples.add_example([l for l in split_line(stripped_line)])
scenario.examples.add_example(list(split_line(stripped_line)))
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)
if feature.background and not scenario:
Expand Down
9 changes: 2 additions & 7 deletions src/pytest_bdd/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,7 @@ def parse_arguments(self, name: str) -> dict[str, str] | None:
:return: `dict` of step arguments
"""
match = self.regex.fullmatch(name)
if match is None:
return None
return match.groupdict()
return None if match is None else match.groupdict()

def is_matching(self, name: str) -> bool:
"""Match given name with the step name."""
Expand Down Expand Up @@ -115,7 +113,4 @@ def get_parser(step_name: TStepParser) -> TStepParser:
def get_parser(step_name: str | StepParser) -> StepParser:
"""Get parser by given name."""

if isinstance(step_name, StepParser):
return step_name

return string(step_name)
return step_name if isinstance(step_name, StepParser) else string(step_name)
5 changes: 1 addition & 4 deletions src/pytest_bdd/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,7 @@ def duration(self) -> float:
:return: Step execution duration.
:rtype: float
"""
if self.stopped is None:
return 0

return self.stopped - self.started
return 0 if self.stopped is None else self.stopped - self.started


class ScenarioReport:
Expand Down
13 changes: 5 additions & 8 deletions src/pytest_bdd/scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def find_fixturedefs_for_step(step: Step, fixturemanager: FixtureManager, nodeid
"""Find the fixture defs that can parse a step."""
# happens to be that _arg2fixturedefs is changed during the iteration so we use a copy
fixture_def_by_name = list(fixturemanager._arg2fixturedefs.items())
for i, (fixturename, fixturedefs) in enumerate(fixture_def_by_name):
for fixturename, fixturedefs in fixture_def_by_name:
for pos, fixturedef in enumerate(fixturedefs):
step_func_context = getattr(fixturedef.func, "_pytest_bdd_step_context", None)
if step_func_context is None:
Expand Down Expand Up @@ -244,14 +244,11 @@ def scenario_wrapper(request: FixtureRequest, _pytest_bdd_example: dict[str, str
def collect_example_parametrizations(
templated_scenario: ScenarioTemplate,
) -> list[ParameterSet] | None:
# We need to evaluate these iterators and store them as lists, otherwise
# we won't be able to do the cartesian product later (the second iterator will be consumed)
contexts = list(templated_scenario.examples.as_contexts())
if not contexts:
if contexts := list(templated_scenario.examples.as_contexts()):
return [pytest.param(context, id="-".join(context.values())) for context in contexts]
else:
return None

return [pytest.param(context, id="-".join(context.values())) for context in contexts]


def scenario(
feature_name: str, scenario_name: str, encoding: str = "utf-8", features_base_dir=None
Expand All @@ -263,7 +260,7 @@ def scenario(
:param str encoding: Feature file encoding.
"""
__tracebackhide__ = True
scenario_name = str(scenario_name)
scenario_name = scenario_name
caller_module_path = get_caller_module_path()

# Get the feature
Expand Down

0 comments on commit 3df6735

Please sign in to comment.