首页 > 解决方案 > 如何在 pytest-bdd 的其他步骤中作为参数获得响应和使用

问题描述

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

在功能文件中,我添加了我的帖子、删除、获取、放置案例。我还分开了 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 开始,然后开始使用这种常用方法,但是如何将响应、状态代码传递到此页面?因为我需要验证。简而言之,如何从不同的步骤页面获取响应作为参数?在此处输入图像描述

在此处输入图像描述

标签: pythonapipytest-bdd

解决方案


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

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

  1. 创建一个“上下文”夹具并将其用作步骤中的参数,When Execute PostAPI method with valid data并将Then Status code of response should be 200接收到的响应存储在其中。
  2. 为您使用的 HTTP 客户端创建一个夹具,When Execute PostAPI method with valid data并将其作为参数传递给 step 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


推荐阅读