Logo Search packages:      
Sourcecode: ldtp version File versions

ldtpcodegen.py

#!/usr/bin/env python 
############################################################################
#
#  Linux Desktop Testing Project -  http://ldtp.freedesktop.org
# 
#  Author:
#      S.Venkateswaran (wenkat.s@gmail.com)
#      K.Harishankaran (sp2hari@gmail.com)
#
#  Copyright 2004 - 2006 Novell, Inc.
# 
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Library General Public
#  License as published by the Free Software Foundation; either
#  version 2 of the License, or (at your option) any later version.
# 
#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Library General Public License for more details.
# 
#  You should have received a copy of the GNU Library General Public
#  License along with this library; if not, write to the
#  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
# 
#############################################################################


from xml.dom import minidom
from string import *
import os,sys, traceback

class LdtpExecutionError (Exception):
      def __init__(self, value):
            self.value = value
      def __str__(self):
            return repr (self.value)

def parsexml (path, output_file):
      """ Parser to produce the python script based on the xml 
          Input:  The Xml file thats generated from the record utility
          Output: LDTP Python Script """

      try:      
            xmldoc = minidom.parse (path)
            record = xmldoc.firstChild #To remove the XML tag (optional).
            childs = record.childNodes
            length = len (childs)
            context = 'ukn'
            ldtpDebug = os.getenv ('LDTP_DEBUG')
            for i in range (length):
                  command = childs[i]
                  if command.nodeName == '#text':
                        continue     # Ignore all '\n' nodes
                  elif command.nodeName == 'COMMAND':
                        try:
                              context = generatecommand (command, context, output_file) #Every command is generated here.
                        except:
                              if ldtpDebug != None:
                                    print '\nTags value may be Null in'
                                    print command.toxml ()
                  elif command.nodeName == 'SLEEP':
                        attributes = command.childNodes
                        output_file.write ('\twait (' + attributes[0].nodeValue + ')\n')
                  else:
                        if ldtpDebug != None:
                              print 'Tag ', command.nodeName, ' type unknown'
      except:
            if ldtpDebug != None:
                  print 'Tags are either not generated properly or not closed properly'
            raise LdtpExecutionError ('Tags are either not generated properly or not closed properly ' + str (traceback.format_exc ()))

def generatecommand (command, previous_context, output_file):
      """ This function is used to a generate the python command for a 
          particular action performed by the user. """
      python_command = ''
      attributes = command.childNodes
      length = len (attributes)
      ldtpDebug = os.getenv ('LDTP_DEBUG')
      for i in range (length):
            # Action Values as added as such. This shud be either fixed here or while generating the action value.
            if attributes[i].nodeName == 'ACTION':
                  value = attributes[i].childNodes[0]
                  if value.nodeName == '#text':
                        if value.nodeValue == 'SELECTMENU':
                              python_command = 'selectmenuitem'
                        elif value.nodeValue == 'SETTEXT':
                              python_command = 'settextvalue'
                        elif value.nodeValue == 'SELECTTAB':
                              python_command = 'selecttabindex'
                        else:
                              python_command = lower (value.nodeValue)
                        python_command = python_command + ' ('
                  else:
                        if ldtpDebug != None:
                              print 'Unknown nodeName ' + value.nodeName

            elif attributes[i].nodeName == 'WINDOW':
                  value = attributes[i].childNodes[0]
                  if value.nodeName == '#text':
                        if value.nodeValue == 'frame': 
                              window = 'frm'
                        elif value.nodeValue == 'dialog':
                              window = 'dlg'
                        elif value.nodeValue == 'alert':
                              window = 'dlg'
                        elif value.nodeValue == 'font chooser':
                              window = 'dlg'
                        elif value.nodeValue == 'file chooser':
                              window = 'dlg'
                        else:
                              window = 'ukn'

                        python_command = python_command + '\'' + window 
                        current_context = window
                  else:
                        if ldtpDebug != None:
                              print 'Unknown nodeName ' + value.nodeName
                  
            # Change this if the <OBJECTTYPE> is changed accordingly 
            elif attributes[i].nodeName == 'OBJECTTYPE':
                  value = attributes[i].childNodes[0]
                  if value.nodeName == '#text':
                        object_type = value.nodeValue
                  else:
                        if ldtpDebug != None:
                              print 'Unknown nodeName ' + value.nodeName

            elif attributes[i].nodeName == 'CONTEXT':
                  value = attributes[i].childNodes[0]
                  if value.nodeName == '#text':
                        context = value.nodeValue.replace (' ', '') 
                        python_command = python_command + context + '\','

                        current_context = window + context
                  else:
                        if ldtpDebug != None:
                              print 'Unknown nodeName ' + value.nodeName

            # TODO: check for every other object_type
            elif attributes[i].nodeName == 'COMPONENT':
                  value = attributes[i].childNodes[0]

                  if value.nodeName == '#text':
                        component = ''
                        if object_type == 'menu item' or object_type == 'radio menu item':
                              menu_path = value.nodeValue.split (';')
                              for i in range (0, len (menu_path) - 1):
                                    component = component + 'mnu' + menu_path[i].replace (' ', '') + ';'
                              component = component + 'mnu' + menu_path[i+1]
                        elif object_type == 'push button':
                              component = 'btn' + value.nodeValue
                        elif object_type == 'toggle button' :
                              component = 'tbtn' + value.nodeValue
                        elif object_type == 'page tab list':
                              component =  value.nodeValue.replace (' ', '')
                        elif object_type == 'table':  
                              component = 'tbl' + value.nodeValue
                        elif object_type == 'combo box':    
                              if value.nodeValue.startswith ('cbo'):
                                    component = value.nodeValue
                              else :
                                    component = 'cbo' + value.nodeValue
                        elif object_type == 'text':
                              if value.nodeValue.startswith ('txt'):
                                    component = value.nodeValue
                              else:
                                    component = 'txt' + value.nodeValue
                        elif object_type == 'check box':
                              component = 'chk' + value.nodeValue
                        elif object_type == 'tree table':
                              component = 'ttbl' + value.nodeValue
                        elif object_type == 'spin button':
                              component = 'sbtn' + value.nodeValue
                        else:
                              if ldtpDebug != None:
                                    print 'Unknown OBJECTTYPE' + object_type 
                        component = component.replace (' ', '')
                        component = component.replace ('.', '')
                        component = component.replace (':', '')
                  else:
                        if ldtpDebug != None:
                              print 'Unknown nodeName ' + value.nodeName

                  python_command = python_command + '\'' + component + '\''

            elif attributes[i].nodeName == 'ARGUMENTS':
                  argument = attributes[i].childNodes
                  for i in range (0, len (argument)):
                        python_command = add_argument (python_command, argument[i]) 
            else:
                  if ldtpDebug != None:
                        print 'Unknown tag ' + attributes[i].nodeName + ' inside <COMMAND>'
      python_command = python_command + ')'
      if previous_context != current_context:
            output_file.write ('\twaittillguiexist (\'' + replace (current_context, ' ', '') + '\')\n')
      output_file.write ('\t' + python_command + '\n')
      return current_context

def add_argument (python_command, argument):
      """ To Add the extra arguments provided in the xml file"""
      if argument.childNodes[0].nodeValue.isdigit ():
            python_command = python_command + ', ' + argument.childNodes[0].nodeValue 
      else:
            python_command = python_command + ', \'' + argument.childNodes[0].nodeValue + '\''
      return python_command

def data_xml (command, output_file):
      data_xml = ''
      attributes = command.childNodes
      length = len (attributes)
      for i in range (length):
            # Action Values as added as such. This shud be either fixed here or while generating the action value.
            if attributes[i].nodeName == "COMPONENT":
                  component = attributes[i].childNodes[0].nodeValue
                  component = component.replace (' ', '')
                  component = component.replace ('.', '')
                  component = component.replace (':', '')
            elif attributes[i].nodeName == 'ARGUMENTS':
                  argument = attributes[i].childNodes
                  for i in range (0, len (argument)):
                        arg = argument[i].childNodes[0].nodeValue
                        output_file.write ("<" + component + ">" + arg  + "</" + component  + ">\n")
                  
def generate_python_code (xml_filepath, python_filepath):
      """Generates the python code for a given xml file produced by the server.
      Returns 0 when the python code is written properly and -1 if there is some error"""
      #print  "In generate_python_code ",xml_filepath, python_filepath
      if os.access (xml_filepath, os.R_OK) == 0:
            return -1
      output_file = open (python_filepath + ".py", "w")
      output_file.write ("#!/usr/bin/env python\n\n")

      output_file.write ("\n\n<<<Include your license here>>>\n\n\n")
      output_file.write ("from ldtp import *\nfrom ldtputils import *\n")
      output_file.write ("try:\n")
      parsexml (xml_filepath, output_file)
      output_file.write ("except:\n")
      output_file.write ("\traise LdtpExecutionError ('Execution Failed')\n")
      return 0

def generate_data_xml (xml_filepath, dataxml_filepath):
      """Generates the data xml for a given xml file by the server
      Returns 0 when the python code is written properly and -1 if there is some error"""
      try:      
            xmldoc = minidom.parse (xml_filepath)
            record = xmldoc.firstChild #To remove the XML tag (optional).
            childs = record.childNodes
            length = len (childs)
            context = 'ukn'
            output_file = open (dataxml_filepath+".xml", "w")
            output_file.write ("<?XML version=\"1.0\" encoding=\"utf-8\">\n<DATA>\n")
            for i in range (length):
                  command = childs[i]
                  if command.nodeName == '#text':
                        continue     # Ignore all '\n' nodes
                  elif command.nodeName == 'ARGUMENT':
                        try:
                              data_xml (command,  output_file) #Every data is generated here.
                        except:
                              if ldtpDebug != None:
                                    print '\nTags value may be Null in'
                                    print command.toxml ()
            output_file.write ("</DATA>\n")
      except:
            if ldtpDebug != None:
                  print 'Tags are either not generated properly or not closed properly'   

Generated by  Doxygen 1.6.0   Back to index