推荐的组织方式
存放 feature 的方式
features│├──frontend│ ││ └──auth│ ││ └──login.feature└──backend│└──auth│└──login.feature
存放测试文件的方式
tests│└──functional│└──test_auth.py│└ """Authentication tests."""from pytest_bdd import scenario@scenario('frontend/auth/login.feature')def test_logging_in_frontend():pass@scenario('backend/auth/login.feature')def test_logging_in_backend():pass
灵魂拷问
- 如何指定运行哪些 features 或者 scenarios 呢?
- 使用标记,和 @pytest.mark 差不多的原理
标记 🌰
mark.feature
# 给 Feature 标记@articleFeature: Resource owner# 给 Scenario 标记@authorScenario: I'm the authorGiven I'm an authorAnd I have an article@adminScenario: I'm the adminGiven I'm the adminAnd there's an article
test_mark.py
from pytest_bdd import given, scenarios# scenarioscenarios('mark.feature')@given("I'm an author", target_fixture="author")def author():print("I'm an author")return dict(username="polo")@given("I'm the admin", target_fixture="author")def admin():print("I'm an admin")return dict(username="admin")@given("I have an article")@given("there's an article")def article(author):print("two given")return author
命令行运行
# 选择 Feature 级别的标记pytest -m "article"# 选择 Scenario 级别的标记pytest -m "author"# 多个 Scenario 级别的标记pytest -m "author or admin"# Feature + Scenariopytest -m "article and admin"
hook
可以通过实现 pytest_bdd_apply_tag 钩子并从中返回 True 来自定义标签如何转换为 pytest 标记
在测试用例目录下创建 conftest.py
添加以下代码
import pytestdef pytest_bdd_apply_tag(tag, function):if tag == 'article':print(function)marker = pytest.mark.skip(reason="Not implemented yet")marker(function)return Trueelse:return False
再次命令行运行
pytest -sq -m "article"
运行结果
<function _get_scenario_decorator.<locals>.decorator.<locals>.scenario_wrapper at 0x10b1d1750><function _get_scenario_decorator.<locals>.decorator.<locals>.scenario_wrapper at 0x10b1d1870>15 deselected in 0.02s
刚刚会运行的两条测试用例这次不会运行了,因为通过 hook 标记为 skip
