我正在尝试测试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
如何动态构建这些行?
答案 0 :(得分:1)
如果确实需要使用每个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_if_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
答案 1 :(得分:-1)