如何使用 pytest-bdd 在 Python 中进行 BDD 风格的测试

2023-04-13 00:00:00 pytest 如何使用
  1. 安装 pytest-bdd
pip install pytest-bdd
  1. 创建测试目录结构

在项目根目录下创建一个名为 features 的目录,并在其中创建一个名为 test_example.feature 的文件。

project/
├── features/
│   └── test_example.feature
├── tests/
└── ...
  1. 编写测试用例

test_example.feature 文件中编写测试用例。例如:

Feature: Login feature 

  Scenario: User logs in with valid credentials 
    Given the user is on the login page 
    When the user enters valid username "pidancode.com" and valid password "secret" 
    And clicks the login button 
    Then the user should be redirected to the home page 

  Scenario: User logs in with invalid credentials 
    Given the user is on the login page 
    When the user enters invalid username "pidancode.com" and invalid password "incorrect" 
    And clicks the login button 
    Then an error message should be displayed 
  1. 编写步骤实现代码

features 目录下创建一个名为 steps 的目录,并在其中创建一个名为 test_example.py 的文件。

test_example.py 文件中,编写步骤实现代码。使用 @given@when@then@and 装饰器指定步骤类型。例如:

from pytest_bdd import scenarios, given, when, then, parsers

scenarios("../features/test_example.feature", example_converters=dict(username=str, password=str))

@given("the user is on the login page")
def user_is_on_login_page():
    pass

@when(parsers.parse('the user enters valid username "{username}" and valid password "{password}"'))
def user_enters_valid_credentials(username, password):
    pass

@when(parsers.parse('the user enters invalid username "{username}" and invalid password "{password}"'))
def user_enters_invalid_credentials(username, password):
    pass

@when("clicks the login button")
def clicks_login_button():
    pass

@then("the user should be redirected to the home page")
def user_redirected_to_home_page():
    pass

@then("an error message should be displayed")
def error_message_displayed():
    pass
  1. 运行测试

在项目根目录下,运行以下命令运行测试:

pytest

或者使用以下命令只运行 BDD 风格的测试:

pytest features/

相关文章