pytest_bdd after_step demo
时间: 2023-07-21 22:04:45 浏览: 134
Certainly! Here's an example of how you can use the `@after_step` hook in pytest-bdd to perform actions after each step in your BDD scenarios.
```python
import pytest
from pytest_bdd import scenario, given, when, then, after_step
@scenario('demo.feature', 'Add two numbers')
def test_add_numbers():
pass
@given("I have two numbers <a> and <b>")
def numbers(a, b):
return int(a), int(b)
@when("I add the numbers")
def add_numbers(numbers):
return sum(numbers)
@then("I expect the result <result>")
def expect_result(add_numbers, result):
assert add_numbers == int(result)
@after_step
def take_screenshot(request):
# Code to take a screenshot after each step
# Replace this with your own implementation
if request.node.rep_call.failed:
# Take a screenshot only if the step failed
# You can use any screenshot library or code here
print("Taking a screenshot")
# You can define multiple after_step hooks if needed
@after_step
def log_step(request):
# Code to log the step details after each step
# Replace this with your own implementation
print(f"Step '{request.node.name}' finished")
```
In this example, we define two `@after_step` hooks. The first `take_screenshot` hook takes a screenshot after each step if the step failed. You can replace the placeholder code with your own implementation to capture screenshots.
The second `log_step` hook logs the details of each step after it finishes. You can replace the placeholder code with your own logging logic.
To run the tests and see the `@after_step` hooks in action, execute `pytest` in your terminal.
Note that the `@after_step` hook is executed after each step, regardless of whether the step passed or failed. You can use it to perform various actions such as logging, capturing screenshots, cleaning up resources, etc., based on your testing requirements.
阅读全文