Behave - 列舉



列舉用於將多個不同的基於字串的單詞對映到值。

我們可能需要一個具有以下特徵的使用者定義資料型別:

  • 必須匹配少數幾個單詞。

  • 在測試執行之前預定義值。

對於上述場景,可以使用基於字串的列舉。

特性檔案

考慮一個名為“支付流程”的特性檔案的示例,如下所示:

Feature − Payment Process
Scenario − Response
      When User asks "Is payment done?"
      Then response is "No"

在步驟實現檔案中,TypeBuilder.make_enum 函式評估為提供的單詞或字串列舉提供的正則表示式模式。register_type 方法用於註冊使用者定義的型別,該型別可以在匹配步驟時解析任何型別轉換。

此外,我們將傳遞引數:用“{}”括起來的使用者定義列舉資料型別。

相應的步驟實現檔案

上面特性檔案的步驟實現檔案如下所示:

from behave import *
from behave import register_type
from parse_type import TypeBuilder
# -- ENUM: Yields True (for "yes"), False (for "no")
parse_response = TypeBuilder.make_enum({"yes": True, "no": False})
register_type(Response=parse_response)
@when('User asks "{q}"')
def step_question(context, q):
   print("Question is: ")
   print(q)
@then('response is "{a:Response}"')
def step_answer(context, a):
   print("Answer is: ")
   print(a)

輸出

執行特性檔案後獲得的輸出如下所示。這裡,我們使用了命令behave --no-capture -f plain

Enumeration Data Type

輸出顯示“支付完成了嗎?”“False”。輸出 False 來自列舉資料型別。

廣告

© . All rights reserved.