python - 生成嵌套字典中所有可能的组合

标签 python testing python-itertools

我需要测试所有可能的安装配置。配置保存在字典数组中,有时包含嵌套数组。

这是配置信息的示例(实际配置要长得多):

config = {'database': 'sqlite',
          'useExisting': False,
          'userCredentials': {'authType': 'windows', 
                              'user': r'.\Testing', 
                              'password': 'testing'
                             }
         }

对于 database,选项为 ['sqlite','mysql','oracle'],对于 useExisting,选项为[对,错]。我可以弄清楚如何完成这些排列的所有排列。

但是对于userCredentials,选项可能完全不同。如果authTypedatabase,我需要额外的参数。我可以创建一个函数来循环并创建所有有效的组合,但如何加入它们?或者有更好的方法来生成配置吗?

userCredentials 也可能有不同的设置。例如,我有两个用户帐户,testing1 和testing2。我需要使用两个用户帐户运行测试,最好使用所有可能的配置。当像这样嵌套时,我无法弄清楚如何递归生成所有配置。

最佳答案

这是您要找的吗?它构建使用 intertools.product 列出的数据库、useExisting 和 authType 的所有组合。 。如果 authType 是“database”,它将使用附加参数更新 userCredentials。根据需要修改:

from itertools import product

def build_config(db,flag,authType,userPass):
    config = dict(database=db,useExisting=flag)
    config['userCredentials'] = {
        'authType': authType, 
        'user': userPass[0], 
        'password': userPass[1]
    }
    if authType == 'database':
        config['userCredentials'].update(
            dict(extra=1,param=2))
    return config

database = ['sqlite','mysql','oracle']
useExisting = [True, False]
authType = ['windows','database']
userPass = [('testing1','pass1'),('testing2','pass2')]

for options in product(database,useExisting,authType,userPass):
    config = build_config(*options)
    print config

关于python - 生成嵌套字典中所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178291/

相关文章:

python - 如何正确设置 python3 的路径?

python - 如何在 C++ 中进行 Python 风格的字符串切片

ruby-on-rails - ActionMailer 测试中的未定义方法 'assert_select_email' [Rails 3.2.13]

ruby - 使用 Rspec 测试 Goliath + Grape

python - 与 itertools.dropwhile 相反(如何在 N 次迭代后停止生成器)

Python-如何将字典作为输入

python - 用 matplotlib 显示每一行的最终 y 轴值

database - 在 Play Framework 中测试 Actors 但数据库已关闭

python - 在 iter 上并行化循环

python - 如何使用三角矩阵使 np.where 更高效?