Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are Behave's decorators created/declared?

I am currently using Behave (BDD for Python) and have been digging in the source code to understand how the @given, @when and @then decorators are being declared.

The farthest I've gone is to look at step_registry.py where I found the function setup_step_decorators(context=None, registry=registry) which appears to be doing the job.

However, I don't quite understand how these decorators are created since they don't appear to be explicitly declared in the source code in the form of a def when(...):. I am under the impression that they are declared based on a list of strings (for step_type in ('given', 'when', 'then', 'step'):) that is then processed by a call to make_decorator().

Can someone walk me through the code and explain where/how these decorators are being declared?

Here is where you can get access to the source code of Behave.

like image 308
Ben Avatar asked Aug 09 '26 13:08

Ben


1 Answers

Well, let's start at the outside:

if context is None:
    context = globals()
for step_type in ('given', 'when', 'then', 'step'):
    step_decorator = registry.make_decorator(step_type)
    context[step_type.title()] = context[step_type] = step_decorator

I think it's the last line that confuses you.

Every module's global namespace is just a dictionary. The function globals() returns that dictionary. If you modify that dictionary, you create new module globals. For example:

>>> globals()['a'] = 2
>>> a
2

In this case, by default, context = globals(). So, for, say, the first step_type, you're effectively doing this:

>>> globals()['given'] = step_decorator
like image 177
abarnert Avatar answered Aug 11 '26 03:08

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!