为什么以下 pytest-bdd 代码会抛出错误:
pytest_bdd.exceptions.StepDefinitionNotFoundError:找不到步骤定义:给出“我有一个空的购物车
这是功能文件:
Feature: Shopping Cart
As a customer
I want to add products to my shopping cart
So that I can purchase them later
Scenario Outline: Add products to the shopping cart
Given I have an empty shopping cart
When I add <product> to the cart
Then the cart should contain <product> and shelf number is <shelf_num>
Examples:
| product | shelf_num |
| Apples | 5 |
| Bananas | 24 |
| Oranges | 11 |
步骤如下:
scenarios('scenario_example_demo.feature')
@pytest.fixture
def shopping_cart():
return []
@given('I have an empty shopping cart')
def empty_shopping_cart(shopping_cart):
assert len(shopping_cart) == 0
@when(parsers.parse('I add {product} to the cart'))
def add_product(shopping_cart, product):
shopping_cart.append(product)
@then(parsers.parse('the cart should contain {product} and shelf number is {shelf_num}'))
def verify_cart_contents(shopping_cart, product,shelf_num):
assert product in shopping_cart and int(shelf_num)>0
奇怪的是,当我将功能文件中的“Given”更改为“When”并在步骤代码中执行相同操作时,代码可以正常工作。
代码来源:来自 Medium (Ramkumar R)
问题出在功能文件的语法上。
Given
、When
、Then
子句属于同一范围,因此应该对齐(例如,从同一行位置开始)。
在您的情况下,
When
和Then
相对于Given
缩进,因此它们被视为子项(我认为这在这种情况下没有实际意义)。
所以,解决方法很简单,添加一个空格:
...
Scenario Outline: Add products to the shopping cart
Given I have an empty shopping cart
When I add <product> to the cart
Then the cart should contain <product> and shelf number is <shelf_num>
请注意,空格数量(例如缩进)并不重要,重要的是对齐方式。