how to fail the step explicitly in behave step implementation

Viewed 5689

I want to explicitly fail the step in behave when I encounter an exception

eg. I am writing the code according to behave documentation -

from behave import *

@when('verify test fails.*?(?P<param_dict>.*)')
def test_logger(context, param_dict):
    try:
        logger.info("testing the logger. this is info message")
        logger.info(1/0)
    except Exception as e:
        logger.error("arrived at exception: "+str(e))
        fail("failed with exception: "+str(e))

but it throws this error:

NameError: name 'fail' is not defined

I tried other ways too, but nothing works eg. context.failed = True (did not work either)

If I do not try to fail explicitly, final test result becomes PASS even if it goes in exception block ...which is weird.

2 Answers

As @Verv mentioned in their answer, a behave step will be marked as failed whenever an exception is thrown, so you could just re-raise the exception.

However, behave will show the backtrace for normal exceptions, whereas you probably just want to show a specific failure message.

For that, raise an AssertionError. In your code, that would look like this:

except Exception as e:
  logger.error("arrived at exception: " + str(e))
  raise AssertionError("failed with exception: " + str(e))

If behave encounters an AssertionError, it will fail the step, display the message you instantiate the error with, but not display other exception stuff.

Related