how to fail the step explicitly in behave step implementation

别说谁变了你拦得住时间么 提交于 2021-02-16 18:27:29

问题


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.


回答1:


context.failed is only an attribute set by Behave and doesn't do anything as is. It's an information attribute, and while you can use it to determine a fail-case and throw an assertion error, it will not do anything on it's own. See context.failed

As for the fail method you've mentioned, it is probably from the unittest module, as seen here. This module is used in Behave's development tests (see their Github) as well. I'll agree though, that this should be clarified in their documentation.

To fix your error you'd need to import the unittest module. To explicitly fail the step, you'd just raise the exception after you've logged your message, something like this:

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



回答2:


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.



来源:https://stackoverflow.com/questions/46274276/how-to-fail-the-step-explicitly-in-behave-step-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!