Friday, June 25, 2010

STAX automation: Converting a property file into a Python dict() object

Coming back to test automation, where I reiterate my fondness of the STAX/STAF framework.

Trying to read the contents of a properties file containing “key=value” pairs, I found this article on how to write the entire thing in Python (the underlying scripting language for STAX scripts) : A few minutes trying to visualize how to embed it into a STAX “script” construct, I realized I did not have the same constraints of not being able to use Java and could write the far more simple construct:


<function name="read_properties" scope="local">

        Returns a Python dict object representing the keys found inside a properties file.

        <function-required-arg name="properties_file">
            Properties file to be read. 

            from java.util import Properties
            from java.lang import String
            from import File
            from import FileInputStream
            from import IOException       

            env_exception = None
            props = Properties()
                fis = None
                    file = File(properties_file)
                    fis = FileInputStream(file)
                    props_dict = {}
                    prop_names = props.propertyNames();
                    for i in range(props.size()):
                        prop_name = prop_names.nextElement()
                        prop_value = props.getProperty(prop_name)
                        props_dict.setdefault(prop_name, prop_value)

                except IOException, e:
                    env_exception = e.getMessage()
                if fis != None:

        <if expr="env_exception != None">                
                    err_msg = 'Attempt to load properties file %s resulted in exception %s'  % (properties_file, env_exception)
                <message log="STAXLogMessage">err_msg</message>                                                    
                <throw exception="'STAXException'">err_msg</throw>
                <message log="STAXLogMessage">
                    'Environment [%s] is %s' % (properties_file, props_dict)