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
Whenstep we are checking if nextThenstep contains"is raised".If so, we mark this
Whenstep as "expected to fail".During needed
Whenstep execution we check corresponding flag and usepytest.raisesmethod to handle it.For first two steps I use pytest_bdd_before_step hook and
requestfixture. And for 3rd I just define some functionhandle_stepright 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_failureto decide whether to usepytest.raisesor not.As an option you can use callable fixture (requesting
requestfixture) to store this function and avoid usingrequest.node.step.expect_failurein such keywords.Also you can add functionality to define allowed exceptions and so on.
test_exception.py
exc.feature
conftest.py