如何在 pytest-bdd 的其他步骤中作为参数获得响应和使用

问题描述

我尝试使用 pytest-bdd 为我的 API Python 项目进行设计。我制作了“common、features、test”文件夹。

功能文件中,我添加了我的帖子、删除获取、放置案例。我也把 post.feature delete.feature 等分开了,因为有丢失的案例。

然后我从功能文件生成了我的 post_steps.py。并且在所有步骤页面中都有一些通用步骤。所以我决定把它们放在 common 文件夹下的 commonsteps.py 中。

然后,在common.py中,有一些常见的方法如下断言状态码:

  @then('Status code of response should be 200')
    def status_code_of_response_should_be_200():
        assert status_code == 200
     

我的测试从 mypost.py 开始,然后开始使用这种常用方法,但是如何将响应、状态代码传递到此页面?因为我需要验证。 简而言之,如何从不同的步骤页面获得响应作为参数?在此处输入图像描述

enter image description here

解决方法

我不太确定您实际尝试实现的目标... 我假设您想知道如何将在步骤 When Execute PostAPI method with valid data 中收到的响应对象传递到步骤 Then Status code of response should be 200

有多种解决方案,它们使用相同的概念:

  1. 创建一个“上下文”fixture 并将其用作步骤 When Execute PostAPI method with valid dataThen Status code of response should be 200 中的参数,并将接收到的响应存储在其中。
  2. 为您在 When Execute PostAPI method with valid data 中使用的 HTTP 客户端创建一个装置,并在步骤 Then Status code of response should be 200 中将其作为参数传递。然后您就可以访问那里的 HTTP 客户端,大概也可以访问响应。

示例:

使用上下文对象

@pytest.fixture
def step_context():
    return {'response': None}

@when("Execute PostAPI method with valid data")
def do_post(step_context):
    # Do HTTP request and retrieve response here ...
    step_context['response'] = response

@then("Status code of response should be 200")
def assert_status(step_context):
    assert step_context['response'].status_code == 200

HTTP 客户端作为夹具

@pytest.fixture
def http_client():
    return HTTPClient()

@when("Execute PostAPI method with valid data")
def do_post(http_client):
    # Do HTTP request and retrieve response here ...
    
@then("Status code of response should be 200")
def assert_status(http_client):
    assert http_client.status_code == 200

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...