如何使用迭代工具来简化这个嵌套的for循环?
# pytest file:
def get_test_cases():
with open("file_path.yml", "r", encoding="utf-8") as index_file:
data = yaml.safe_load(index_file)
for vendor_dict in data:
for vendor_name, class_list in vendor_dict.items():
for class_dict in class_list:
for class_name, method_list in class_dict.items():
for method_dict in method_list:
for function, test_list in method_dict.items():
for test_case in test_list:
yield vendor_name, class_name, function, test_case
@pytest.mark.parametrize("iteration", get_test_cases())
def test_network(iteration, monkeypatch):
"""Performs pytest using info provided from test case"""
(vendor_name, class_name, function, test_case) = iteration
# Use data above to perform pytest
# Code omitted
样本数据以YAML格式显示:
# YAML file:
- cisco:
- CiscoClass:
- get_interface_stats:
- test_description: "test interface stats"
function_input: "Gig1/1/1"
expected_output: "show interfaces Gig1/1/1"
- juniper:
- JuniperClass:
- get_vlan_info:
- test_description: "test get_vlan_info"
function_input: "10"
expected_output: "show vlan 10"
解释
YAML文件包含用于构建测试用例的参数。我们为Cisco提供了一组测试用例,为Juniper提供了其他测试用例。所以这个结构是这个供应商->类的名称->函数->测试用例数据。
我的pytest文件中的函数get_test_cases将加载YAML文件内容,然后遍历内容,并为每个测试用例生成数据。函数test_network使用这些数据,并执行实际测试。
我试图找到一个替代嵌套的for循环,以便我可以提高我的皮棉评级.如果这是可能的话。
发布于 2022-07-16 20:55:23
您可以尝试以下方法使其更紧凑:
def testcases(data, level=0):
if level == 3:
for case in data:
yield (case,)
else:
for record in data:
for name in record:
for case in testcases(record[name], level + 1):
yield (name,) + case
或
def testcases(data, level=0):
if level == 6:
for case in data:
yield (case,)
elif level % 2 == 0:
for record in data:
yield from testcases(record, level + 1)
else:
for name, records in data.items():
for case in testcases(records, level + 1):
yield (name,) + case
然后
def get_test_cases():
with open("file_path.yml", "r", encoding="utf-8") as index_file:
data = yaml.safe_load(index_file)
yield from testcases(data)
使用您的示例文件如下
for case in get_test_cases():
print(case)
产
('cisco', 'CiscoClass', 'get_interface_stats', {'test_description': 'test interface stats', 'function_input': 'Gig1/1/1', 'expected_output': 'show interfaces Gig1/1/1'})
('juniper', 'JuniperClass', 'get_vlan_info', {'test_description': 'test get_vlan_info', 'function_input': '10', 'expected_output': 'show vlan 10'})
https://stackoverflow.com/questions/73002476
复制相似问题