如何在VSCode UI中运行特定pytest-bdd场景?
在VSCode UI中运行单个pytest-bdd场景的解决方案
我需要在VSCode UI中运行特定的pytest-bdd场景,目前UI仅能运行类中所有场景,单个场景无法正常执行。
项目结构
tests |-- features |-- sample_tests.feature |-- step_defs |-- test_example.py
sample_tests.feature 内容
Feature: Sample tests Scenario: Test number one Given I have 100 pounds Then I have money @second Scenario: Test number two Given I open some page Then I verify the header is displayed
test_example.py 内容
import os import logging logger = logging.getLogger(__name__) cwd = os.getcwd() full_path = f"{cwd}/tests/features/sample_test.feature" # 注意:此处文件名拼写错误,应为sample_tests.feature @scenario(full_path, 'Test number one') def test_method_name(): logger.info("End of the first test") pass @given("I have 100 pounds") def hundred_pounds(): logger.info("Inside I have 100 pounds") @then("I have money") def have_money(): logger.info("Inside I have money") @scenario(full_path, 'Test number two') def test_first_browser_test(): logger.info("End of the second test") pass @given("I open some page") def open_page(driver): driver.get("www.google.com") logger.info("google opened") @then("I verify the header is displayed") def verify_page(): logger.info("Second browser step")
当前运行现状
- 运行
test_example.py会执行两个测试场景 - 单独运行
test_method_name或test_first_browser_test无任何效果(需解决的核心问题) - 点击
test_example.py的「转到测试」会跳转到对应文件 - 点击
test_method_name或test_first_browser_test的「转到测试」会跳转到/lib/python3.9/site-packages/pytest_bdd/scenario.py
已在VSCode和PyCharm中测试,结果一致。目前仅能通过命令行运行特定场景(如pytest -m "second"),但希望通过UI实现该操作。
解决方法
1. 修复文件路径拼写错误
首先检查到test_example.py中拼接的feature文件名有误:sample_test.feature应为sample_tests.feature(多了一个s)。路径错误会导致测试函数无法正确关联到feature场景,这是单个测试无法运行的核心原因之一。修正后的路径代码:
full_path = f"{cwd}/tests/features/sample_tests.feature"
2. 使用相对路径替代绝对路径
避免依赖os.getcwd()带来的路径问题,直接使用相对于项目根目录的路径:
from pytest_bdd import scenario @scenario("tests/features/sample_tests.feature", "Test number one") def test_method_name(): pass
pytest会自动从项目根目录开始解析路径,无需手动拼接绝对路径。
3. 配置VSCode测试探索器
在VSCode的settings.json中确保pytest配置正确,让测试探索器能正确识别pytest-bdd的测试函数:
{ "python.testing.pytestArgs": [ "tests" ], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true }
配置完成后重新加载窗口,测试面板会正确列出所有单个场景对应的测试函数,此时即可点击运行单个测试。
4. 利用场景标记筛选运行
对于已标记的场景(如@second),可以在VSCode测试面板的搜索框中输入@second,筛选出对应场景的测试函数,直接点击运行即可。
内容的提问来源于stack exchange,提问作者Kamil
相关产品推荐
相关产品推荐

