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) : http://code.activestate.com/recipes/496795-a-python-replacement-for-javautilproperties/. 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">
<function-prolog>
Returns a Python dict object representing the keys found inside a properties file.
</function-prolog>
<function-map-args>
<function-required-arg name="properties_file">
Properties file to be read.
</function-required-arg>
</function-map-args>
<sequence>
<script>
from java.util import Properties
from java.lang import String
from java.io import File
from java.io import FileInputStream
from java.io import IOException
env_exception = None
props = Properties()
try:
fis = None
try:
file = File(properties_file)
fis = FileInputStream(file)
props.load(fis)
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()
finally:
if fis != None:
fis.close()
</script>
<if expr="env_exception != None">
<sequence>
<script>
err_msg = 'Attempt to load properties file %s resulted in exception %s' % (properties_file, env_exception)
</script>
<message log="STAXLogMessage">err_msg</message>
<throw exception="'STAXException'">err_msg</throw>
</sequence>
<else>
<message log="STAXLogMessage">
'Environment [%s] is %s' % (properties_file, props_dict)
</message>
</else>
</if>
<return>props_dict</return>
</sequence>
</function>


0 comments:
Post a Comment