You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当字典值为嵌套列表格式时,如何提取对应元素作为测试用例参数循环运行

解决方法

首先注意两个前置问题:

  • 你当前JSON配置中Operation数组只有4个元素,其余File_locations、Null_values、weights都是5个元素,执行前建议补全Operation的第5个元素,避免下标越界
  • 你原测试用例中写的config["Operations"]多了后缀s,和JSON配置里的键名Operation不一致,需要修改一致避免读取失败

方案1:手动写for循环遍历下标执行

先加载JSON配置,再通过下标提取同位置的参数,循环执行用例:

import json
# 第一步:加载JSON配置文件
with open("你的配置文件存储路径.json", "r", encoding="utf-8") as f:
    config = json.load(f)

# 取所有配置数组的最小长度,避免下标越界
case_total = min(
    len(config["File_locations"]),
    len(config["Operation"]),
    len(config["Null_values"]),
    len(config["weights"])
)

# 测试执行逻辑
def test_run_all_cases(self):
    self.dqopenPage = DqOpenPage(self.driver)
    # 遍历所有测试用例下标
    for idx in range(case_total):
        # 提取当前下标对应的所有参数
        cur_files = config["File_locations"][idx]
        cur_operation = config["Operation"][idx][0] # Operation存的是嵌套列表,取第一个元素即可拿到操作名称
        cur_null = config["Null_values"][idx][0] # Null_values同理取嵌套列表的第一个值
        cur_weights = config["weights"][idx] # 权重配置是字典直接取值

        # 执行当前用例
        self.dqopenPage.drop(filess = cur_files)
        self.dqopenPage.df_operation(operation = cur_operation)
        self.dqopenPage.define_null_value(null = cur_null)
        # 可在此处添加测试结果断言、执行日志记录逻辑

方案2:测试框架参数化实现(更推荐)

如果你用的是pytest、unittest这类单元测试框架,更推荐用参数化功能实现,每个用例独立执行,不会因为前序用例失败影响后续用例的运行和结果统计,以pytest为例:

import pytest
import json
from selenium import webdriver

# 预加载配置生成测试参数列表
with open("你的配置文件存储路径.json", "r", encoding="utf-8") as f:
    config = json.load(f)
case_total = min(
    len(config["File_locations"]),
    len(config["Operation"]),
    len(config["Null_values"]),
    len(config["weights"])
)
# 生成参数列表,每个元素对应一个测试用例的入参
test_param_list = [
    (
        config["File_locations"][idx],
        config["Operation"][idx][0],
        config["Null_values"][idx][0],
        config["weights"][idx]
    ) for idx in range(case_total)
]

class TestDqFunction:
    # 所有用例执行前初始化一次driver和页面对象
    def setup_class(self):
        self.driver = webdriver.Chrome(executable_path=config["Chrome_executable_path"])
        self.dqopenPage = DqOpenPage(self.driver)

    # 把参数列表注入测试用例,自动循环执行
    @pytest.mark.parametrize("files, operation, null_val, weights", test_param_list)
    def test_single_case(self, files, operation, null_val, weights):
        self.dqopenPage.drop(filess = files)
        self.dqopenPage.df_operation(operation = operation)
        self.dqopenPage.define_null_value(null = null_val)
        # 在此处添加测试断言逻辑

内容的提问来源于stack exchange,提问作者aishg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:48:05