Search code examples
pythonunit-testingconfigparser

How to tell Configparser to open the config file, that has the same name, as the module, opening it?


I'm writing a testing framework using Python's unittest. I have separate modules for separate parts of the tested application (part1 - part1.py, part2 - part2.py etc.). I want to create a helper module, which will read configuration settings for each of the modules, with the config file name being the same as the module name (part1.py - part1.conf, part2.py - part2.conf). Config files will reside in the same folder as the modules do. When I run part1.py I need to tell the tests that config for them is in part1.conf. How do I do that? This helper module will not necessarily reside in the same folder as the test modules. I do not want to use nose because I want to have as little external dependencies as possible.


Solution

  • def module_config(mod):
        '''Loads the config residing next to the module.'''
        import configparser, os.path
        cp = configparser.ConfigParser()
        cp.read_file(open(os.path.splitext(mod.__file__)[0] + '.conf'))
        return cp
    
    # load config for some module
    import some_module
    module_config(some_module)
    
    # load config for current module
    module_config(sys.modules(__name__))