我创建了一个Django应用程序,并且非常依赖pytest
来发现和组织我的单元和功能测试。但是,我希望在未来的测试中应用behave
开发驱动的行为。不幸的是,behave
测试特性不能由pytest
自动检测.
如何将behave
pytest
及其测试集成到pytest
发现、执行和报告中?
发布于 2016-12-14 20:18:58
Pytest和是两个独立的测试运行程序。
有一个用于行为测试的pytest插件,它也使用Gherkin作为DSL,但是这些步骤的实现使用了与行为不同的语法,所以我认为您不能直接运行用它创建的步骤。
发布于 2021-02-19 20:24:02
遵循pytest文档示例,您可以实现如下的输出:
______________________________________________________________ Feature: Fight or flight - Scenario: Stronger opponent ______________________________________________________________
Feature: Fight or flight
Scenario: Stronger opponent
Step [OK]: the ninja has a third level black-belt
Step [ERR]: attacked by Chuck Norris
Traceback (most recent call last):
File ".venv/lib/python3.6/site-packages/behave/model.py", line 1329, in run
match.run(runner.context)
File ".venv/lib/python3.6/site-packages/behave/matchers.py", line 98, in run
self.func(context, *args, **kwargs)
File "tests/bdd/steps/tutorial.py", line 23, in step_impl4
raise NotImplementedError('STEP: When attacked by Chuck Norris')
NotImplementedError: STEP: When attacked by Chuck Norris
Step [NOT REACHED]: the ninja should run for his life
使用来自行为教程的特性文件
为了使pytest运行正常,可以在conftest.py
中使用以下代码片段
# content of conftest.py
import pytest
class BehaveException(Exception):
"""Custom exception for error reporting."""
def pytest_collect_file(parent, path):
"""Allow .feature files to be parsed for bdd."""
if path.ext == ".feature":
return BehaveFile.from_parent(parent, fspath=path)
class BehaveFile(pytest.File):
def collect(self):
from behave.parser import parse_file
feature = parse_file(self.fspath)
for scenario in feature.walk_scenarios(with_outlines=True):
yield BehaveFeature.from_parent(
self,
name=scenario.name,
feature=feature,
scenario=scenario,
)
class BehaveFeature(pytest.Item):
def __init__(self, name, parent, feature, scenario):
super().__init__(name, parent)
self._feature = feature
self._scenario = scenario
def runtest(self):
import subprocess as sp
from shlex import split
feature_name = self._feature.filename
cmd = split(f"""behave tests/bdd/
--format json
--no-summary
--include {feature_name}
-n "{self._scenario.name}"
""")
try:
proc = sp.run(cmd, stdout=sp.PIPE)
if not proc.returncode:
return
except Exception as exc:
raise BehaveException(self, f"exc={exc}, feature={feature_name}")
stdout = proc.stdout.decode("utf8")
raise BehaveException(self, stdout)
def repr_failure(self, excinfo):
"""Called when self.runtest() raises an exception."""
import json
if isinstance(excinfo.value, BehaveException):
feature = excinfo.value.args[0]._feature
results = excinfo.value.args[1]
data = json.loads(results)
summary = ""
for feature in data:
if feature['status'] != "failed":
continue
summary += f"\nFeature: {feature['name']}"
for element in feature["elements"]:
if element['status'] != "failed":
continue
summary += f"\n {element['type'].title()}: {element['name']}"
for step in element["steps"]:
try:
result = step['result']
except KeyError:
summary += f"\n Step [NOT REACHED]: {step['name']}"
continue
status = result['status']
if status != "failed":
summary += f"\n Step [OK]: {step['name']}"
else:
summary += f"\n Step [ERR]: {step['name']}"
summary += "\n " + "\n ".join(result['error_message'])
return summary
def reportinfo(self):
return self.fspath, 0, f"Feature: {self._feature.name} - Scenario: {self._scenario.name}"
注意:
feature
、element
或step
状态与behave.model_core.Status
中的Enum
进行比较)behave
作为子过程,而不是它的内部API。一个合适的移民应该考虑behave.runner:Runner
、behave.runner:ModelRunner
和触发器。https://stackoverflow.com/questions/41146633
复制相似问题