我如何使用itertools来简化这个嵌套的for循环?



如何使用itertools来简化这个嵌套的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循环,这样我就可以提高我的pylint评级…如果这是可能的话。

您可以尝试以下操作使其更紧凑:

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'})

相关内容

  • 没有找到相关文章

最新更新