问题描述
我尝试使用 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 开始,然后开始使用这种常用方法,但是如何将响应、状态代码传递到此页面?因为我需要验证。 简而言之,如何从不同的步骤页面获得响应作为参数?在此处输入图像描述
解决方法
我不太确定您实际尝试实现的目标...
我假设您想知道如何将在步骤 When Execute PostAPI method with valid data
中收到的响应对象传递到步骤 Then Status code of response should be 200
。
有多种解决方案,它们使用相同的概念:
- 创建一个“上下文”fixture 并将其用作步骤
When Execute PostAPI method with valid data
和Then Status code of response should be 200
中的参数,并将接收到的响应存储在其中。 - 为您在
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