Search code examples
pythontestingpython-itertools

Generating all possible combinations in a nested dictionary


I need to test all possible installation configurations possible. The configurations are kept in a dictionary array that sometimes contains nested arrays.

Here's a sample of the configuration information (actual configuration is much longer):

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

For database, options are ['sqlite','mysql','oracle'], and for useExisting, the options are [True, False]. I can figure out how to go through all permutations of those.

But for userCredentials, the options can be quite different. If authType is database, I need additional parameters. I can create a function that'll loop through and create all valid combinations, but how do I join them? Or is there a better way to generate the configurations?

The userCredentials may also have different settings. For instance, I have two user accounts, testing1 and testing2. I'll need to run the tests with both user accounts, and preferably with all possible configurations. I'm having trouble figuring out how to recursively generate all configurations when it's nested like this.


Solution

  • Is this what you are looking for? It builds all combinations of database, useExisting, and authType listed using intertools.product. If authType is 'database' it updates the userCredentials with additional parameters. Modify as needed:

    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