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

Sar*_*lis 1 python python-2.7 python-behave

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

行为.ini

[behave.userdata]
url=http://some.url
Run Code Online (Sandbox Code Playgroud)

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

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

nat*_*323 5

首先,对于你来说behave.ini格式很重要。也就是说,记下空格:

[behave.userdata]
url = http://some.url
Run Code Online (Sandbox Code Playgroud)

其次,/features/steps/steps.py应该/features/environment.py. 这是什么environment.py?如果您不知道,它基本上是一个文件,定义了测试运行之前/期间/之后应该发生的情况。请参阅此处了解更多详细信息。

本质上,你会得到类似的东西:

环境.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'])
Run Code Online (Sandbox Code Playgroud)

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

步骤.py

from behave import *

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