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

问题描述 投票:0回答:3

我无法找到如何使用beeve.ini

中的
ApiClient
值初始化我的
context.config.userdata['url']

behave.ini

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

步骤.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
python python-2.7 python-behave
3个回答
5
投票

首先,在您的

behave.ini
中,格式很重要。也就是说,记下空格:

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

其次,您

应该
/features/steps/steps.py中创建它,而不是在
/features/environment.py
中创建ApiClient对象。这是什么
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'])

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

步骤.py

from behave import *

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

1
投票

我知道这是一个非常古老的问题,但答案不是最新的。当前文档中似乎不需要空格,OP 的问题是标题标签。一定是

[behave]

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


0
投票

我认为没有办法,除非您将 APIClient 设置为步骤文件并将身份验证作为步骤定义的一部分。请记住,您可以拥有实际上不是在功能级别使用的步骤的步骤定义,而只是作为 context.execute_step“某个步骤定义”执行。

© www.soinside.com 2019 - 2024. All rights reserved.