行为:访问步骤定义之外的context.config变量

时间:2018-06-13 12:12:40

标签: python python-2.7 python-behave

我无法找到一种方法如何使用来自behave.ini的值ApiClient初始化context.config.userdata['url']

behave.ini

[behave.userdata]
url=http://some.url

steps.py

from behave import *
from client.api_client import ApiClient

# This is where i want to pass the config.userdata['url'] value
api_calls = ApiClient('???') 


@given('I am logged as "{user}" "{password}"')
def login(context, user, password):
    context.auth_header = api_calls.auth(user, password)

api_client.py

class ApiClient(object):

    def __init__(self, url):
        self.url = url

    def auth(self, email, password):
        auth_payload = {'email': email, 'password': password}
        auth_response = requests.post(self.url + '/api/auth/session', auth_payload)

        return auth_response.text

2 个答案:

答案 0 :(得分:2)

首先,在您的behave.ini格式重要中。也就是说,记下空格:

[behave.userdata]
url = http://some.url

其次,不是在/features/steps/steps.py中创建ApiClient对象,而是/features/environment.py内创建它。这个environment.py是什么?如果您不知道,它基本上是一个文件,用于定义测试运行之前/期间/之后应该发生的事情。有关详细信息,请参阅here

基本上,你会有类似的东西:

<强> environment.py

from client.api_client import ApiClient

""" 
The code within the following block is checked before all/any of test steps are run.
This would be a great place to instantiate any of your class objects and store them as
attributes in behave's context object for later use.
"""
def before_all(context):         
    # The following creates an api_calls attribute for behave's context object
    context.api_calls = ApiClient(context.config.userdata['url'])

稍后,当您想要使用ApiClient对象时,您可以这样做:

<强> steps.py

from behave import *

@given('I am logged as "{user}" "{password}"')
def login(context, user, password):
    context.api_calls.auth(user, password)

答案 1 :(得分:0)

我知道这是一个非常老的问题,但答案不是最新的。在当前文档中似乎不需要空格,OP的问题是标头标记。它必须是[behave]

https://behave.readthedocs.io/en/latest/behave.html