【问题标题】:How are Behave's decorators created/declared?Behave 的装饰器是如何创建/声明的?
【发布时间】:2014-08-08 22:57:49
【问题描述】:

我目前正在使用 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() 进行处理。

谁能带我浏览代码并解释这些装饰器在哪里/如何声明?

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

【问题讨论】:

    标签: python bdd python-decorators python-behave


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      它们在第 90 行附近被注入到globals()(此时context 是globals(),因为context 是None):

      # -- Create the decorators
      def setup_step_decorators(context=None, registry=registry):
          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() 就像普通字典一样工作):

      >>> a
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      NameError: name 'a' is not defined
      >>> globals()['a'] = 5
      >>> a
      5
      

      【讨论】:

      • 几乎和我在同一时间完全相同的例子。但是,在这样的示例中使用的 正确 数字当然是 2,而不是 5。:)
      • @abarnert 我注意到了,奇怪的是我们都想到了'a'。可能 42 是最好的 (or maybe 3)
      • 太棒了。非常感谢大家,这正是我想要的。我倾向于同意这个例子用 42 更容易理解:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2016-11-26
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      相关资源
      最近更新 更多