I would like to define a scenario as follows:
Scenario: An erroneous operation
Given some data
And some more data
When I perform an operation
Then an exception is raised
Is there a good way to do this so that the when
step isn't actually called until a pytest.raises
context manager can be constructed for it? I could use a callable fixture, but that's going to pollute all other uses of the "I perform an operation"
step.
I'm not sure that I understood your question correctly, but aren't you trying to achieve something like this?
Before each
When
step we are checking if nextThen
step contains"is raised"
.If so, we mark this
When
step as "expected to fail".During needed
When
step execution we check corresponding flag and usepytest.raises
method to handle it.For first two steps I use pytest_bdd_before_step hook and
request
fixture. And for 3rd I just define some functionhandle_step
right in test module. Of course you should move it somewhere else. This function requiresstep
(which is just some defined function with your code) andrequest.node.step.expect_failure
to decide whether to usepytest.raises
or not.As an option you can use callable fixture (requesting
request
fixture) to store this function and avoid usingrequest.node.step.expect_failure
in such keywords.Also you can add functionality to define allowed exceptions and so on.
test_exception.py
exc.feature
conftest.py