#!/usr/bin/python
#
# gathers all Actions in pyMoleCuilder module and tests them with some default
# values.
#
# date: Oct 5, 2011
# author: Gregor Bollerhey

import pyMoleCuilder as mol
import sys, re, subprocess

cmds =  filter(lambda s: s[0] != '_', dir(mol))

# options.dat einlesen

Defaults = {}

with open('options.dat') as f:
    for line in f:
        if len(line) > 0 and line[0] != '#':
            key, value = line.split('\t', 1)
            value = value[1:-2] # quotes entfernen
        
            Defaults[key] = value

# aufrufen

Allparams = []

def ParseParameters(docstring):
    result = []
    params = re.findall(r'\(str\)([-a-zA-Z]*)', docstring)

    for param in params:
        if not param in Allparams:
            Allparams.append(param)
            
            if not param in Defaults:
                print 'Fehlender Defaultwert:', param
        
        # direkt substituieren, oder erst beim aufruf?
        if param in Defaults:
            param = Defaults[param]
        
        result.append(param)

    return result

for cmd in cmds:
    doc = eval('mol.%s.__doc__' % cmd)
    params = ParseParameters(doc)
    
    print '--BEGIN-- %s mit %s --------' % (cmd, params)
   
    # write command to file
    output=open("test.py", "w")
    output.write('import pyMoleCuilder as mol\nparams = %s\nmol.%s(*params)\n' % (params, cmd))
    output.close()
    # call python externally on this file and catch retcode
    p = subprocess.Popen(["python", "test.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    print ' --- STDOUT ---'
    print ' %s ' % (stdout)
    print ' --- STDERR ---'
    print ' %s ' % (stderr)
    retcode = p.returncode
    if retcode == 134 or retcode == 0:
      print ' ---- ok ----'
    else:
      print ' -- FAILED with %s --' % (retcode)
    #exec('mol.%s(*params)' % cmd)
    
    print '---END--- %s mit %s --------' % (cmd, params)

sys.exit(0)
