gpt4 book ai didi

python - 用pytest创建动态参数?

转载 作者:太空狗 更新时间:2023-10-30 01:36:40 28 4
gpt4 key购买 nike

我正在尝试测试我的 REST API 的各种端点。一些端点采用其他端点提供的值。例如:

  • 查询/locations获取可用位置列表以及它们是否已启用
  • 查询/inventory?loc_id=<id>并传入位置 ID 以获取特定位置的库存列表
  • 查询/inventory/<id>/details获取与一个特定库存 ID 关联的属性列表

在我的测试中,我想遍历整个工作流程(检查特定位置库存项目的特定属性)。通常,我会用一对 @parameterize 构建一个 pytest 函数装饰器,但在这种情况下,我无法提前知道所有 ID。

我通常会做什么:

@pytest.mark.parametrize('location', ['1', '2', '3', 'HQ'])
@pytest.mark.parametrize('inventory_id', [1, 2, 3])
def test_things(location, inventory_id):
# Call /inventory/inventory_id/details and check attributes

第二行是个问题,因为我不知道 inventory_id不用打电话/inventory第一的。 inventory_id 也完全有可能在特定位置不可用。

我想做什么:

Query /location to build a list of IDs to add to the first parameterize line
Query `/inventory?loc_id=<id>` and build a list of IDs to pass to the second parameterize line

我怎样才能动态地构建这些线?

最佳答案

如果您真的想用每个 inventory_id 测试每个位置,您可以在测试前计算这些列表

def get_locations_list(...):
locations = []
# query locations
...
return locations

LOCATIONS = get_locations_list()
INVENTORY_IDS = get_inventory_ids()

@pytest.mark.parametrize('location', LOCATIONS)
@pytest.mark.parametrize('inventory_id', INVENTORY_IDS)
def test_things(location, inventory_id):
# test stuff

如果库存 ID 取决于位置,那么您可以准备元组列表:

def get_locations_and_ids():
list_of_tuples = []
...
for location in locations:
ids = ...
for id in ids:
list_of_tuples.append( (location, id) )
return list_of_tuples

LIST_OF_TUPLES = get_locations_and_ids()

@pytest.mark.parametrize(('location', 'inventory_id'), LIST_OF_TUPLES)
def test_things(location, inventory_id):
# ...

您还可以使用 pytest-generate-tests 模式,如下所述:

https://docs.pytest.org/en/latest/parametrize.html#basic-pytest-generate-tests-example

关于python - 用pytest创建动态参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45843289/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com