Behave 的装饰器是如何创建/声明的?

Ben*_*Ben 3 python bdd python-decorators python-behave

我目前正在使用 Behave(用于 Python 的 BDD)并且一直在挖掘源代码以了解@given,@when@then装饰器是如何声明的。

我走得最远的是看看step_registry.py我在哪里找到了setup_step_decorators(context=None, registry=registry)似乎在做这项工作的功能。

但是,我不太明白这些装饰器是如何创建的,因为它们似乎没有在源代码中以def when(...):. 我的印象是它们是基于字符串 ( for step_type in ('given', 'when', 'then', 'step'):)列表声明的,然后通过调用make_decorator().

有人可以引导我完成代码并解释这些装饰器的声明位置/方式吗?

您可以在此处访问Behave源代码

aba*_*ert 5

好吧,让我们从外部开始:

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
Run Code Online (Sandbox Code Playgroud)

我认为这是最后一行让你感到困惑。

每个模块的全局命名空间只是一个字典。该函数globals()返回该字典。如果修改该字典,则会创建新的模块全局变量。例如:

>>> globals()['a'] = 2
>>> a
2
Run Code Online (Sandbox Code Playgroud)

在这种情况下,默认情况下,context = globals(). 因此,对于第一个step_type,您正在有效地执行以下操作:

>>> globals()['given'] = step_decorator
Run Code Online (Sandbox Code Playgroud)