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

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

我离开的最远的是查看step_registry.py,在那里我找到了函数setup_step_decorators(context = None,registry = registry),它似乎正在完成这项工作.

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

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

您可以在这里访问source code of Behave.

最佳答案 好吧,让我们从外面开始吧:

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

我认为这是困扰你的最后一行.

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

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

在这种情况下,默认情况下,context = globals().所以,对于第一个step_type,你实际上是这样做的:

>>> globals()['given'] = step_decorator
点赞