Exemple #1
0
    def order_scenes(self, scene_list):
        ''' Orders scenes from the massloader.  Be sure to call verifyscenes before allowing this to happen '''

        client = SoapClient(self.get_url("massloader"))
        tramorder = client.factory.create('order')
        tramscenes = client.factory.create('scenes')
        tramorder.scenes = tramscenes
        for scene in scene_list:
            tramscene = client.factory.create('scene')
            tramscene.sceneId = scene.name
            tramscene.productName = self.get_product_code(scene.name)
            tramscene.recipeId = null()
            tramscene.unitComment = null()
            tramscene.parameters = null()
            tramorder.scenes.scene.append(tramscene)
        tramorder.externalRefNumber = '111111'
        tramorder.orderComment = null()
        tramorder.priority = 5
        #tramorder.registrationId = '252380'
        tramorder.registrationId = self.get_tram_id()
        tramorder.requestor = 'EE'
        tramorder.roleId = null()

        try:
            response = client.service.submitOrder(tramorder)
            return response
        except Exception, e:
            print("An error occurred submitting the order to tram: %s" % (e))
            #log error
            return -1
Exemple #2
0
    def order_scenes(self, scene_list):
        ''' Orders scenes from the massloader.  Be sure to call verifyscenes before allowing this to happen '''

        client = SoapClient(self.get_url("massloader"))
        tramorder = client.factory.create('order')
        tramscenes = client.factory.create('scenes')
        tramorder.scenes = tramscenes
        for scene in scene_list:
            tramscene = client.factory.create('scene')
            tramscene.sceneId = scene.name
            tramscene.productName = self.get_product_code(scene.name)
            tramscene.recipeId = null()
            tramscene.unitComment = null()
            tramscene.parameters = null()
            tramorder.scenes.scene.append(tramscene)
        tramorder.externalRefNumber = '111111'
        tramorder.orderComment = null()
        tramorder.priority = 5
        #tramorder.registrationId = '252380'
        tramorder.registrationId = self.get_tram_id()
        tramorder.requestor = 'EE'
        tramorder.roleId = null()
    
        try:
            response = client.service.submitOrder(tramorder)
            return response
        except Exception, e:
            print ("An error occurred submitting the order to tram: %s" % (e))
            #log error
            return -1
 def test_null(self):
     p = self.factory.create('types:ABIntegerDict')
     p.a = null()
     p.b = null()
     q = self.factory.create('types:ABIntegerDict')
     q.a = null()
     q.b = null()
     res = self.service.add_integer_dicts(p, q)
     self.assertEqual(res.a, 0)
     self.assertEqual(res.b, 0)
Exemple #4
0
 def test_null(self):
     p = self.factory.create('types:ABStringDict')
     p.a = null()
     p.b = null()
     q = self.factory.create('types:ABStringDict')
     q.a = null()
     q.b = null()
     res = self.service.add_string_dicts(p, q)
     self.assertEqual(res.a, None)
     self.assertEqual(res.b, None)
Exemple #5
0
 def test_null(self):
     p = self.factory.create('types:ABStringDict')
     p.a = null()
     p.b = null()
     q = self.factory.create('types:ABStringDict')
     q.a = null()
     q.b = null()
     res = self.service.add_string_dicts(p, q)
     self.assertEqual(res.a, None)
     self.assertEqual(res.b, None)
Exemple #6
0
def main():
    wsOpts = WSOpts()
    parser = wsOpts.get_common_opts()

    (options, args) = parser.parse_args()
    wsOpts.setLogging(options.debug)

    if wsOpts.checkRequiredMissing(options, ()):
        parser.print_help()
        sys.exit(-1)

    configServiceClient = ConfigServiceClient(options)
    defectServiceClient = DefectServiceClient(options)

    a = configServiceClient.client.service.getAttribute({'name':'custom'})
    attrDefSpec = configServiceClient.client.factory.create('attributeDefinitionSpecDataObj')
    attrDefSpec.attributeName='custom'
    attrDefSpec.attributeType=a.attributeType
    attrDefSpec.showInTriage=a.showInTriage
    attrDefSpec.description='attempt to get something to change'
    changeSpec = configServiceClient.client.factory.create('attributeValueChangeSpecDataObj')
    changeSpec.attributeValueIds=[]
    changeSpec.attributeValues=[]
    attribValId = configServiceClient.client.factory.create('attributeValueId')
    attribVal = configServiceClient.client.factory.create('attributeValueSpecDataObj')
    attribValId.name = 'four'
    attribVal.name = 'five'
    changeSpec.attributeValueIds.append(attribValId)
    changeSpec.attributeValues.append(attribVal)
    attribValId = configServiceClient.client.factory.create('attributeValueId')
    attribVal = configServiceClient.client.factory.create('attributeValueSpecDataObj')
    attribValId = null()
    attribVal.name = 'one'
    changeSpec.attributeValueIds.append(attribValId)
    changeSpec.attributeValues.append(attribVal)
    attribValId = configServiceClient.client.factory.create('attributeValueId')
    attribVal = configServiceClient.client.factory.create('attributeValueSpecDataObj')
    attribValId = null()
    attribVal.name = 'two'
    changeSpec.attributeValueIds.append(attribValId)
    changeSpec.attributeValues.append(attribVal)
    attribValId = configServiceClient.client.factory.create('attributeValueId')
    attribVal = configServiceClient.client.factory.create('attributeValueSpecDataObj')
    attribValId = null()
    attribVal.name = 'three'
    changeSpec.attributeValueIds.append(attribValId)
    changeSpec.attributeValues.append(attribVal)
    print changeSpec
    attrDefSpec.attributeValueChangeSpec=changeSpec
    print a.attributeDefinitionId
    print attrDefSpec
    configServiceClient.client.service.updateAttribute(a.attributeDefinitionId, attrDefSpec)
    print configServiceClient.client.service.getAttribute({'name':'custom'})
Exemple #7
0
def basic_rpc_literal():

    global errors

    try:
        url = "http://localhost:7080/rhq-rhq-enterprise-server-ejb3/WebServiceRPCTestBean?wsdl"
        start(url)
        client = Client(url)
        print client
        #
        # create name
        #
        name = client.factory.create("name")
        name.first = u"jeff" + unichr(1234)
        name.last = "ortel"
        #
        # create a phone object using the wsdl
        #
        phoneA = client.factory.create("phone")
        phoneA.npa = 410
        phoneA.nxx = 555
        phoneA.number = 5138
        phoneB = client.factory.create("phone")
        phoneB.npa = 919
        phoneB.nxx = 555
        phoneB.number = 4406
        #
        # create a person object using the wsdl
        #
        person = client.factory.create("person")
        print person
        person.name = name
        person.age = 43
        person.phone.append(phoneA)
        person.phone.append(phoneB)
        print person
        #
        # addPerson()
        #
        print "addPersion()"
        result = client.service.addPerson(person)
        print "\nreply(\n%s\n)\n" % result
        #
        # create a new name object used to update the person
        #
        newname = client.factory.create("name")
        newname.first = "Todd"
        newname.last = None
        #
        # update the person's name (using the webservice)
        #
        print "updatePersion()"
        result = client.service.updatePerson(person, newname)
        print "\nreply(\n%s\n)\n" % str(result)
        result = client.service.updatePerson(person, null())
        print "\nreply(\n%s\n)\n" % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
    def ensuds(self, dictionary):
        """
        Turn a dictionary into a soap structure as defined by the wsdl
        from pyresponse.Api used when instantiating the API wrapper.
        Dictionaries become paintArrays, key, value pairs from the
        dictionary become paintKeyValuePair objects.

        Also manages encoding of keys and values.
        ------------------------------------------------
        @param dictionary                - dictionary of request data
        @return result                   - soap representation of that same data
        """
        if not dictionary:
            return null()
        array = self.factory.create('paintArray')
        for key in dictionary:
            pair = self.factory.create('paintKeyValuePair')
            setattr(pair, 'key', self.x_encode(key, 'ignore'))
            value = getattr(pair, 'value')
            if isinstance(dictionary[key], dict):
                setattr(value, 'arr', self.ensuds(dictionary[key]))
            elif isinstance(dictionary[key], str) or isinstance(dictionary[key], unicode):
                escaped = self.x_encode(dictionary[key], 'xmlcharrefreplace')
                if isinstance(dictionary[key], unicode) and not key.isdigit() and not (key in self.main.encoding_exceptions):
                    (key, escaped) = self.base_encode(getattr(pair, 'key'), escaped)
                    setattr(pair, 'key', key)

                setattr(value, 'str', escaped)
            else:
                setattr(value, 'str', str(dictionary[key]))
            getattr(array, 'pairs').append(pair)
        return array
Exemple #9
0
def basic_rpc_literal():

    global errors

    try:
        url = 'http://localhost:7080/rhq-rhq-enterprise-server-ejb3/WebServiceRPCTestBean?wsdl'
        start(url)
        client = Client(url)
        print client
        #
        # create name
        #
        name = client.factory.create('name')
        name.first = u'jeff' + unichr(1234)
        name.last = 'ortel'
        #
        # create a phone object using the wsdl
        #
        phoneA = client.factory.create('phone')
        phoneA.npa = 410
        phoneA.nxx = 555
        phoneA.number = 5138
        phoneB = client.factory.create('phone')
        phoneB.npa = 919
        phoneB.nxx = 555
        phoneB.number = 4406
        #
        # create a person object using the wsdl
        #
        person = client.factory.create('person')
        print person
        person.name = name
        person.age = 43
        person.phone.append(phoneA)
        person.phone.append(phoneB)
        print person
        #
        # addPerson()
        #
        print 'addPersion()'
        result = client.service.addPerson(person)
        print '\nreply(\n%s\n)\n' % result
        #
        # create a new name object used to update the person
        #
        newname = client.factory.create('name')
        newname.first = 'Todd'
        newname.last = None
        #
        # update the person's name (using the webservice)
        #
        print 'updatePersion()'
        result = client.service.updatePerson(person, newname)
        print '\nreply(\n%s\n)\n' % str(result)
        result = client.service.updatePerson(person, null())
        print '\nreply(\n%s\n)\n' % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
Exemple #10
0
    def set_wiki_content(self, content):
        """method set_wiki_content updates the wiki for the current Plan

        Args:
            Content (str or Text object)

        Returns:
            None

        References:
            Planning.setPlanWikiContent
        """
        self._verify_obj()
        if content:
            if isinstance(content, basestring):
                obj_content = Text(content=content)
                suds_content = obj_content._suds_object
            elif isinstance(content, Text):
                suds_content = content._suds_object
            else:  # is a suds object
                suds_content = content
        else:
            suds_content = suds.null()
        self.session.planning_client.service. \
            setPlanWikiContent(self.uri, suds_content)
def _PackForSuds(obj, factory):
    """Packs SOAP input into the format we want for suds.

  The main goal here is to pack dictionaries with an 'xsi_type' key into
  objects. This allows dictionary syntax to be used even with complex types
  extending other complex types. The contents of dictionaries and lists/tuples
  are recursively packed. Mutable types are copied - we don't mutate the input.

  Args:
    obj: A parameter for a SOAP request which will be packed. If this is
        a dictionary or list, the contents will recursively be packed. If this
        is not a dictionary or list, the input object is returned unaltered.
    factory: The suds.client.Factory object which can create instances of the
        classes generated from the WSDL.

  Returns:
    If the given obj was a dictionary that contained the 'xsi_type' key, this
    will be an instance of a class generated from the WSDL. Otherwise, this will
    be the same data type as the input obj was.
  """
    if obj in ({}, None):
        # Force suds to serialize empty objects. There are legitimate use cases for
        # this, for example passing in an empty SearchCriteria object to a DFA
        # search method in order to select everything.
        return suds.null()
    elif isinstance(obj, dict):
        if "xsi_type" in obj:
            try:
                new_obj = factory.create(obj["xsi_type"])
            except suds.TypeNotFound:
                new_obj = factory.create(":".join(["ns0", obj["xsi_type"]]))
            # Suds sends an empty XML element for enum types which are not set. None
            # of Google's Ads APIs will accept this. Initializing all of the fields in
            # a suds object to None will ensure that they don't get serialized at all
            # unless the user sets a value. User values explicitly set to None will be
            # packed into a suds.null() object.
            for param, _ in new_obj:
                # Another problem is that the suds.mx.appender.ObjectAppender won't
                # serialize object types with no fields set, but both AdWords and DFP
                # rely on sending objects with just the xsi:type set. The below "if"
                # statement is an ugly hack that gets this to work in all(?) situations
                # by taking advantage of the fact that these classes generally all have
                # a type field. The only other option is to monkey patch ObjectAppender.
                if param.endswith(".Type"):
                    setattr(new_obj, param, obj["xsi_type"])
                else:
                    setattr(new_obj, param, None)
            for key in obj:
                if key == "xsi_type":
                    continue
                setattr(new_obj, key, _PackForSuds(obj[key], factory))
        else:
            new_obj = {}
            for key in obj:
                new_obj[key] = _PackForSuds(obj[key], factory)
        return new_obj
    elif isinstance(obj, (list, tuple)):
        return [_PackForSuds(item, factory) for item in obj]
    else:
        return obj
Exemple #12
0
def _PackForSuds(obj, factory):
    """Packs SOAP input into the format we want for suds.

  The main goal here is to pack dictionaries with an 'xsi_type' key into
  objects. This allows dictionary syntax to be used even with complex types
  extending other complex types. The contents of dictionaries and lists/tuples
  are recursively packed. Mutable types are copied - we don't mutate the input.

  Args:
    obj: A parameter for a SOAP request which will be packed. If this is
        a dictionary or list, the contents will recursively be packed. If this
        is not a dictionary or list, the input object is returned unaltered.
    factory: The suds.client.Factory object which can create instances of the
        classes generated from the WSDL.

  Returns:
    If the given obj was a dictionary that contained the 'xsi_type' key, this
    will be an instance of a class generated from the WSDL. Otherwise, this will
    be the same data type as the input obj was.
  """
    if obj in ({}, None):
        # Force suds to serialize empty objects. There are legitimate use cases for
        # this, for example passing in an empty SearchCriteria object to a DFA
        # search method in order to select everything.
        return suds.null()
    elif isinstance(obj, dict):
        if 'xsi_type' in obj:
            try:
                new_obj = factory.create(obj['xsi_type'])
            except suds.TypeNotFound:
                new_obj = factory.create(':'.join(['ns0', obj['xsi_type']]))
            # Suds sends an empty XML element for enum types which are not set. None
            # of Google's Ads APIs will accept this. Initializing all of the fields in
            # a suds object to None will ensure that they don't get serialized at all
            # unless the user sets a value. User values explicitly set to None will be
            # packed into a suds.null() object.
            for param, _ in new_obj:
                # Another problem is that the suds.mx.appender.ObjectAppender won't
                # serialize object types with no fields set, but both AdWords and DFP
                # rely on sending objects with just the xsi:type set. The below "if"
                # statement is an ugly hack that gets this to work in all(?) situations
                # by taking advantage of the fact that these classes generally all have
                # a type field. The only other option is to monkey patch ObjectAppender.
                if param.endswith('.Type'):
                    setattr(new_obj, param, obj['xsi_type'])
                else:
                    setattr(new_obj, param, None)
            for key in obj:
                if key == 'xsi_type': continue
                setattr(new_obj, key, _PackForSuds(obj[key], factory))
        else:
            new_obj = {}
            for key in obj:
                new_obj[key] = _PackForSuds(obj[key], factory)
        return new_obj
    elif isinstance(obj, (list, tuple)):
        return [_PackForSuds(item, factory) for item in obj]
    else:
        return obj
Exemple #13
0
        def _reset(obj):
            """ Resets all attributes of a suds.Object to null values

                The default pythonic `None` value would cause them to be
                skipped, not sent.
            """
            for k in obj.__keylist__:
                obj[k] = null()
Exemple #14
0
        def _reset(obj):
            """ Resets all attributes of a suds.Object to null values

                The default pythonic `None` value would cause them to be
                skipped, not sent.
            """
            for k in obj.__keylist__:
                obj[k] = null()
 def __init__(self):
     self._cache = ConnectionCache(no_current_msg='No current client')
     self._imports = []
     self._logger = logger
     self._global_timeout = False
     try:  # exception if Robot is not running
         BuiltIn().set_global_variable("${SUDS_NULL}", null())
     except:
         pass
Exemple #16
0
 def __init__(self):
     self._cache = ConnectionCache(no_current_msg='No current client')
     self._imports = []
     self._logger = logger
     self._global_timeout = True
     self._external_options = weakref.WeakKeyDictionary()
     try:  # exception if Robot is not running
         BuiltIn().set_global_variable("${SUDS_NULL}", null())
     except:
         pass
Exemple #17
0
def resolver_incidencia(id_remedy, usuario, categorizacion, solucion):

    global base_url
    metodo = "WS_JZL_Interfaz"
    url = "%s/%s" % (base_url, metodo)

    # Creamos una pasarela de conexion hacia el WS
    client = suds.client.Client(url)

    # Datos de autenticacion
    token = client.factory.create('AuthenticationInfo')
    token.userName = "******"
    token.password = "******"
    client.set_options(soapheaders=token)

    for nivel in categorizacion:
        if categorizacion[nivel] == "":
            categorizacion[nivel] = suds.null()

    # Array con todos los datos que mandaremos al WS
    datos = dict(
        ID_Incidencia = id_remedy,
        Aplicacion = "GESTOR DE INCIDENCIAS",
        Transaccion = "Modificar Estado Incidencia",
        Codigo_Estado = "01",
        Estado_Incidencia = "Resuelta",
        Tipo = "Consulta",
        Tecnico_Asignado = usuario,
        Nivel_1_Final = categorizacion['nivel_1'],
        Nivel_2_Final = categorizacion['nivel_2'],
        Nivel_3_Final = categorizacion['nivel_3'],
        Nivel_4_Final = categorizacion['nivel_4'],
        Nivel_5_Final = categorizacion['nivel_5'],
        Nivel_6_Final = categorizacion['nivel_6'],
        Solucion = solucion
    )

    try:
        resultado = client.service.setEstadoInc(**datos)
        #print client.last_sent()
        return resultado
    except suds.WebFault, e:
        print "ERROR - %s." % e
        sys.exit(18)
 def __init__(self):
     self._cache = ConnectionCache(no_current_msg='No current client')
     self._imports = []
     self._logger = logger
     self._global_timeout = True
     self._external_options = weakref.WeakKeyDictionary()
     try:
         part = urllib.request.__version__.split('.', 1)
         n = float('.'.join(part))
         if n >= 2.6:
             self._global_timeout = False
     except Exception as e:
         raise e
         self._logger.warn("Failed to get urllib2's version")
         self._logger.debug(traceback.format_exc())
     try:  # exception if Robot is not running
         BuiltIn().set_global_variable("${SUDS_NULL}", null())
     except:
         pass
 def api_make_request(self, bean_type, bean_class, bean_process
   , entity_data = None, process_data = None, no_response = False):
     if self.api_context or (bean_process is PureResponseClient.BEAN_PROCESSES.AUTHENTICATE):
         api_context = self.api_context or suds.null()
         response    = self.api_client.service.handleRequest(
                         api_context
                       , bean_type + '_' + bean_class
                       , bean_process
                       , self._dict_to_ptarr(entity_data)
                       , self._dict_to_ptarr(process_data)
                     )
         if no_response:
             return True
         else:
             return self._ptarr_to_dict(response)
     else:
         return self._dict_err(
             PureResponseClient.ERRORS.NOT_AUTHENTICATED
           , None
         )
 def _dict_to_ptarr(self, dict_):
     """
     Internal use.
     Convert dictionaries to 'paintArray' objects using suds.
     Works some encoding magic in the process in order to be 
     compliant with the expectations and requirements of the 
     API while attempting to maintain the integrity of the 
     data content.
     ----------------------------------------------
     @param dict_        - dictionary of data to convert.
     """
     if not dict_:
         return suds.null()
     arr_ = self.api_client.factory.create(PureResponseClient.TYPES.ARRAY)
     for key_ in dict_:
         kvp_ = self.api_client.factory.create(PureResponseClient.TYPES.KVP)
         setattr(kvp_, PureResponseClient.TYPES.KEYS.KEY, key_.encode('ascii', 'ignore'))
         val_ = getattr(kvp_, PureResponseClient.TYPES.KEYS.VALUE)
         if isinstance(dict_[key_], dict):
             setattr(val_, PureResponseClient.TYPES.KEYS.ARRAY, self._dict_to_ptarr(dict_[key_]))
         elif (isinstance(dict_[key_], str) or 
             (isinstance(dict_[key_], unicode) and self._unicode_exceptions(key_))):
             setattr(val_, PureResponseClient.TYPES.KEYS.STRING, dict_[key_].encode('utf-8'))
         elif isinstance(dict_[key_], unicode):
             setattr(val_, PureResponseClient.TYPES.KEYS.STRING, base64.b64encode(
                 dict_[key_].encode('utf-8')
             ))
             setattr(
                 kvp_
               , PureResponseClient.TYPES.KEYS.KEY
               , getattr(kvp_, PureResponseClient.TYPES.KEYS.KEY) 
                 + PureResponseClient.FIELDS.BASE64_PARTIAL
             )
         else:
             setattr(val_, PureResponseClient.TYPES.KEYS.STRING, str(dict_[key_]))
         getattr(arr_, PureResponseClient.TYPES.KEYS.PAIRS).append(kvp_)
     return arr_
Exemple #21
0
 def test_null(self):
     self.assertEqual(
         self.service.add_integers(null(), null()), 0)
Exemple #22
0
 def test_null_args(self):
     res = self.service.add_string_dicts(null(), null())
     self.assertEqual(res.a, None)
     self.assertEqual(res.b, None)
Exemple #23
0
 def test_null(self):
     self.assertEqual(self.service.flip_boolean(null()), True)
Exemple #24
0
def crear_remedy_FWestandar(nombre_host, ip, estandar, usuario, ip_origen, fecha_solicitud):
    
    hostname = nombre_host.lower()

    global base_url    
    metodo = "WS_JZL_Interfaz"
    url = "%s/%s" % (base_url, metodo)

    # Creamos una pasarela de conexion hacia el WS
    client = suds.client.Client(url)

    # Datos de autenticacion
    token = client.factory.create('AuthenticationInfo')
    token.userName = "******"
    token.password = "******"
    client.set_options(soapheaders=token)

    # Ejecutamos un script externo ya existente para consultar el nombre y apellido en el AD a partir del login
    obtenernombre = "/var/www/ipj/scripts/query_ad-nombre.sh %s" % usuario
    ejecucion = subprocess.Popen(obtenernombre.split(), stdout=subprocess.PIPE)
    nombrecompleto = ejecucion.communicate()[0].strip().split(';')

    # Preparamos las variables que luego le pasaremos al WS
    tipo_estandar = normalizar_nombre_estandar(estandar)

    if nombrecompleto[0] == "NSSapp":
        login = "******"
        nombre = "NSS"
    else:
        login = usuario
        nombre = nombrecompleto[0]

    # Equivalencias de usuarios AD <-> Remedy.
    if usuario == "lpangar":
        login = "******"
    
    if usuario == "vgalfer":
        login = "******"


    remedydescripcion = """[FW] - Creación de reglas estándar %s: %s-%s

Hola,

Necesitamos dar de alta las reglas estándar para el siguiente host:

    Hostname: %s    
    IP: %s
    Estándar: %s

Muchas gracias.

Un saludo, 
%s.

NOTA: Solicitud realizada desde la IP %s el %s por el usuario "%s".""" % (estandar, hostname, ip, hostname, ip, estandar,  nombre, ip_origen, fecha_solicitud, usuario)

    remedytipopeticion = "Petición"

    # Array con todos los datos que mandaremos al WS
    datos = dict(
    CAR_Login_Name = login,
    CAR_Aplicacion = "GESTOR DE INCIDENCIAS",
    CAR_Transaccion = "Crear Incidencia",
    CAR_Codigo_Estado = "01",
    CAR_Estado_Interfase = "Pendiente",
    CAR_Servicio = "PROYECTO",
    CAR_Urgencia = "Normal",
    CAR_Grupo_asignado = "SOP_TECNICO_GESTION_RED",
    CAR_Descripcion = remedydescripcion.decode('UTF-8'),
    SEL_Tipo_Peticion = remedytipopeticion.decode('UTF-8'),
    SEL_Regla_Estandar = "Si",
    SEL_Impacto_Usuarios = suds.null(), 
    CAR_Regla = tipo_estandar,
    CAR_Nivel1 = "FIREWALL PERIMETRO EXTERIOR",
    CAR_Nivel2 = "PETICION",
    CAR_Nivel3 = "PROVISION REGLAS",
    )

    resultado = client.service.crearincidencia(**datos)
    
    codigoestado = resultado['CAR_Codigo_Estado']

    if codigoestado == "03":
        #print resultado['CAR_Descripcion_Interfase']
        #print "Remedy: %s" % resultado['CAR_ID_Registro']
        return resultado['CAR_ID_Registro']
    else:
        print "ERROR - %s." % resultado['CAR_Descripcion_Interfase']
        sys.exit(14)
Exemple #25
0
class SudsLibrary(_ClientManagementKeywords, _FactoryKeywords,
                  _OptionsKeywords, _ProxyKeywords, _SoapLoggingKeywords,
                  _WsseKeywords):
    """SudsLibrary is a library for functional testing of SOAP-based web
    services.

    SudsLibrary is based on [https://fedorahosted.org/suds/|Suds], a dynamic
    SOAP 1.1 client.

    == Case Sensitivy in SudsLibrary ==
    Many things in the world of SOAP are case-sensitive. This includes method
    names, WSDL object names and attributes, and service or port names.

    == Creating and Configuring a Client ==
    If necessary, use keywords `Bind Schema To Location` or `Add Doctor
    Import`. These are rarely needed. Next, `Create Soap Client` to create a Suds
    client. The output from this keyword contains useful information including
    available types and methods. Next, use other keywords to configure the
    client as necessary. `Set Location` is the most commonly needed keyword.

    == Working with WSDL Objects ==
    When Suds digests a WSDL, it creates dynamic types to represent the complex
    types defined by a WSDL or its imports. These types are listed in the
    output of `Create Soap Client`. WSDL objects are used as method arguments,
    attribute values of other WSDL objects, and return values. `Create Wsdl
    Object` is used to create instances of WSDL object types. To see what the
    structure of a WSDL object is, you can do this:
    | ${obj}=        | Create Wsdl Object | someObject |
    | ${obj as str}= | Convert To String  | ${obj}     |
    | Log            | ${obj as str}      |            |
    The same technique can be used to analyze a response object. It may also
    help to use a tool such as Eclipse or SoapUI to comprehend the structures.

    === Getting WSDL Object Attributes ===
    Getting a WSDL object's attribute value may be done with `Get Wsdl Object
    Attribute` or extended variable syntax*. Keywords from other libraries, such
    as _BuiltIn_ and _Collections_ may be used to verify attribute values.
    Examples:
    | ${name}=        | Get Wsdl Object Attribute | ${person} | name |
    | Should Be Equal | ${person.name}            | Bob       |      |

    === Setting WSDL Object Attributes ===
    Setting a WSDL object's attribute value may be done with `Set Wsdl Object
    Attribute` or extended variable syntax*. `Set Wsdl Object Attribute`
    verifies the argument is an object of the correct type and the attribute
    exists.
    | Set Wsdl Object Attribute | ${person}    | name | Tia |
    | ${person.name}=           | Set Variable | Tia  |     |

    * In order to use extended variable syntax, the attribute name must consist
    of only letters, numbers, and underscores.

    == Example Test ==
    The following simple example demonstrates verifying the return value using
    keywords in this library and in the `BuiltIn` and `Collections` libraries.
    You can run this test because it uses a public web service.

    | Create Soap Client         | http://www.webservicex.net/Statistics.asmx?WSDL |               |              |
    | ${dbl array}=              | Create Wsdl Object                              | ArrayOfDouble |              |
    | Append To List             | ${dbl array.double}                             | 2.0           |              |
    | Append To List             | ${dbl array.double}                             | 3.0           |              |
    | ${result}=                 | Call Soap Method                                | GetStatistics | ${dbl array} |
    | Should Be Equal As Numbers | ${result.Average}                               | 2.5           |              |

    The definition of type ArrayOfDouble:
    | <s:complexType name="ArrayOfDouble">
    |   <s:sequence>
    |     <s:element minOccurs="0" maxOccurs="unbounded" name="double" type="s:double"/>
    |   </s:sequence>
    | </s:complexType>
    Note that the attribute name on the ArrayOfDouble-type that is the list of
    numbers is the singular "double". Outside of the WSDL, the structure can
    also be seen in the output of Create Wsdl Object:
    | ${dbl array} = (ArrayOfDouble){
    |   double[] = <empty>
    | }

    The relevant part of the WSDL defining the parameters to the method:
    | <s:element name="GetStatistics">
    |   <s:complexType>
    |     <s:sequence>
    |       <s:element minOccurs="0" maxOccurs="1" name="X" type="tns:ArrayOfDouble"/>
    |     </s:sequence>
    |   </s:complexType>
    | </s:element>
    The definition of this method appears in the output of Create Soap Client
    as:
    | GetStatistics(ArrayOfDouble X, )

    == Passing Explicit NULL Values ==
    If you have a service that takes NULL values for required parameters or
    you want to pass NULL for optional object attributes, you simply need to
    set the value to ${SUDS_NULL}. You need to use ${SUDS_NULL} instead of
    ${None} because None is interpreted by the marshaller as not having a
    value. The soap message will contain an empty (and xsi:nil="true" if node
    defined as nillable). ${SUDS_NULL} is defined during library
    initialization, so editors like RIDE will not show it as defined.

    == Extending SudsLibrary ==
    There may be times where Suds/SudsLibrary does not work using the library
    keywords alone. Extending the library instead of writing a custom one will
    allow you to use the existing keywords in SudsLibrary.

    There are two methods useful for extending SudsLibrary:
    | _client()
    | _add_client(client, alias=None)
    The first can be used to access the current instance of
    suds.client.Client. The second can be used to put a client into the client
    cache that you have instantiated.

    Here is an example demonstrating how to implement a keyword that adds a
    MessagePlugin to the current Suds client (based on the [https://fedorahosted.org/suds/wiki/Documentation#MessagePlugin|Suds documentation]):
    | from robot.libraries.BuiltIn import BuiltIn
    | from suds.plugin import MessagePlugin
    |
    | class _MyPlugin(MessagePlugin):
    |     def marshalled(self, context):
    |         body = context.envelope.getChild('Body')
    |         foo = body[0]
    |         foo.set('id', '12345')
    |         foo.set('version', '2.0')
    |
    | class SudsLibraryExtensions(object):
    |     def attach_my_plugin(self):
    |         client = BuiltIn().get_library_instance("SudsLibrary")._client()
    |         # prepend so SudsLibrary's plugin is left in place
    |         plugins = client.options.plugins
    |         if any(isinstance(x, _MyPlugin) for x in plugins):
    |             return
    |         plugins.insert(0, _MyPlugin())
    |         client.set_options(plugins=plugins)
    """

    ROBOT_LIBRARY_VERSION = VERSION
    ROBOT_LIBRARY_SCOPE = "GLOBAL"
    ROBOT_LIBRARY_DOC_FORMAT = "ROBOT"

    def __init__(self):
        self._cache = ConnectionCache(no_current_msg='No current client')
        self._imports = []
        self._logger = logger
        self._global_timeout = True
        self._external_options = weakref.WeakKeyDictionary()
        try:
            part = urllib2.__version__.split('.', 1)
            n = float('.'.join(part))
            if n >= 2.6:
                self._global_timeout = False
        except Exception, e:
            raise e
            self._logger.warn("Failed to get urllib2's version")
            self._logger.debug(traceback.format_exc())
        try:  # exception if Robot is not running
            BuiltIn().set_global_variable("${SUDS_NULL}", null())
        except:
            pass
Exemple #26
0
    def get_shipping_price(self, shipment_info, packages, shipper, ship_from,
                           ship_to, packaging_type, service_type):
        client = self._set_client(self.rate_wsdl, 'Rate', 'RateRequest')

        request = client.factory.create('ns0:RequestType')
        request.RequestOption = 'Rate'

        classification = client.factory.create('ns2:CodeDescriptionType')
        classification.Code = '00'  # Get rates for the shipper account
        classification.Description = 'Get rates for the shipper account'

        namespace = 'ns2'
        shipment = client.factory.create('{}:ShipmentType'.format(namespace))

        for package in self.set_package_detail(client, packages,
                                               packaging_type, namespace,
                                               ship_from, ship_to):
            shipment.Package.append(package)

        shipment.Shipper.Name = shipper.name or ''
        shipment.Shipper.Address.AddressLine = [
            shipper.street or '', shipper.street2 or ''
        ]
        shipment.Shipper.Address.City = shipper.city or ''
        shipment.Shipper.Address.PostalCode = shipper.zip or ''
        shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''
        if shipper.country_id.code in ('US', 'CA', 'IE'):
            shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''
        shipment.Shipper.ShipperNumber = self.shipper_number or ''
        # shipment.Shipper.Phone.Number = shipper.phone or ''

        shipment.ShipFrom.Name = ship_from.name or ''
        shipment.ShipFrom.Address.AddressLine = [
            ship_from.street or '', ship_from.street2 or ''
        ]
        shipment.ShipFrom.Address.City = ship_from.city or ''
        shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''
        shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''
        if ship_from.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''
        # shipment.ShipFrom.Phone.Number = ship_from.phone or ''

        shipment.ShipTo.Name = ship_to.name or ''
        shipment.ShipTo.Address.AddressLine = [
            ship_to.street or '', ship_to.street2 or ''
        ]
        shipment.ShipTo.Address.City = ship_to.city or ''
        shipment.ShipTo.Address.PostalCode = ship_to.zip or ''
        shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''
        if ship_to.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''
        # shipment.ShipTo.Phone.Number = ship_to.phone or ''
        if not ship_to.commercial_partner_id.is_company:
            shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()

        shipment.Service.Code = service_type or ''
        shipment.Service.Description = 'Service Code'
        if service_type == "96":
            shipment.NumOfPieces = int(shipment_info.get('total_qty'))
        shipment.ShipmentServiceOptions = ''
        shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = suds.null()

        # try:
        # Get rate using for provided detail
        print "=====SENT ======"
        print client.last_sent()
        print "=====REC ======"
        print client.last_received()
        response = client.service.ProcessRate(
            Request=request,
            CustomerClassification=classification,
            Shipment=shipment)
        print "=====SENT ======"
        print client.last_sent()
        print "=====REC ======"
        print client.last_received()
        # Check if ProcessRate is not success then return reason for that
        if response.Response.ResponseStatus.Code != "1":
            return self.get_error_message(
                response.Response.ResponseStatus.Code,
                response.Response.ResponseStatus.Description)

        result = {}
        result['currency_code'] = response.RatedShipment[
            0].TotalCharges.CurrencyCode

        # Some users are qualified to receive negotiated rates
        negotiated_rate = 'NegotiatedRateCharges' in response.RatedShipment[
            0] and response.RatedShipment[
                0].NegotiatedRateCharges.TotalCharge.MonetaryValue or None

        result['price'] = negotiated_rate or response.RatedShipment[
            0].TotalCharges.MonetaryValue
        return result
 def null(self):
     return null()
Exemple #28
0
    def find_adress(self, municipality, type, street, number, find_all,
                    recursive):
        """ Returns a list of dictionaries with the addresses found with the indicated nomenclature """

        print(u"Adress: %s, %s %s %s" % (municipality, type, street, number))

        # We execute the query
        print(u"URL: %s" % self.get_icgc_geoencoder_client().wsdl.url)
        try:
            res_dicts_list = self.get_icgc_geoencoder_client(
            ).service.localitzaAdreca(Poblacio=municipality,
                                      Via={
                                          'Tipus': type,
                                          'Nom': street
                                      },
                                      Portal=null(),
                                      CodiPostal="NO",
                                      Llogaret=null(),
                                      Comarca=null(),
                                      InePoblacio=null(),
                                      TrobaTots=("SI" if find_all else "NO"),
                                      PortalTextual=number)
        except Exception as e:
            print(u"Error: %s SOAP Request: %s" %
                  (e, self.get_icgc_geoencoder_client().last_sent()))
            raise e

        # We convert the result to a unique format
        dicts_list = [{
            'nom':
            "%s" % res_dict['AdrecaXY'],
            'idTipus':
            '',
            'nomTipus':
            'Adreça',
            'nomMunicipi':
            res_dict['Adreca']['Poblacio'],
            'nomComarca':
            res_dict['Adreca']['Comarca']['nom'],
            'x':
            float(res_dict['CoordenadesETRS89UTM']['X'])
            if 'CoordenadesETRS89UTM' in res_dict else None,
            'y':
            float(res_dict['CoordenadesETRS89UTM']['Y'])
            if 'CoordenadesETRS89UTM' in res_dict else None,
            'epsg':
            25831
        } for res_dict in res_dicts_list]

        # We detect locations without coordinates and try to obtain the coordinate by doing the search on the name
        # returned in the initial request
        if recursive:
            for res_dict in dicts_list:
                if not res_dict['x'] or not res_dict['y']:
                    alternative_res_dict_list = self.find_data(res_dict['nom'],
                                                               None,
                                                               recursive=False)
                    if alternative_res_dict_list:
                        alternative_res_dict = alternative_res_dict_list[0]
                        res_dict['x'] = alternative_res_dict['x']
                        res_dict['y'] = alternative_res_dict['y']
        return dicts_list
Exemple #29
0
    def get_shipping_price(self, shipment_info, packages, shipper, ship_from,
                           ship_to, packaging_type, service_type):
        client = self._set_client(self.rate_wsdl, 'Rate', 'RateRequest')

        request = client.factory.create('ns0:RequestType')
        request.RequestOption = 'Rate'

        classification = client.factory.create('ns2:CodeDescriptionType')
        classification.Code = '00'  # Get rates for the shipper account
        classification.Description = 'Get rates for the shipper account'

        namespace = 'ns2'
        shipment = client.factory.create('{}:ShipmentType'.format(namespace))

        for package in self.set_package_detail(client, packages,
                                               packaging_type, namespace,
                                               ship_from, ship_to):
            shipment.Package.append(package)

        shipment.Shipper.Name = shipper.name or ''
        shipment.Shipper.Address.AddressLine = [
            shipper.street or '', shipper.street2 or ''
        ]
        shipment.Shipper.Address.City = shipper.city or ''
        shipment.Shipper.Address.PostalCode = shipper.zip or ''
        shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''
        if shipper.country_id.code in ('US', 'CA', 'IE'):
            shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''
        shipment.Shipper.ShipperNumber = self.shipper_number or ''
        # shipment.Shipper.Phone.Number = shipper.phone or ''

        shipment.ShipFrom.Name = ship_from.name or ''
        shipment.ShipFrom.Address.AddressLine = [
            ship_from.street or '', ship_from.street2 or ''
        ]
        shipment.ShipFrom.Address.City = ship_from.city or ''
        shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''
        shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''
        if ship_from.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''
        # shipment.ShipFrom.Phone.Number = ship_from.phone or ''

        shipment.ShipTo.Name = ship_to.name or ''
        shipment.ShipTo.Address.AddressLine = [
            ship_to.street or '', ship_to.street2 or ''
        ]
        shipment.ShipTo.Address.City = ship_to.city or ''
        shipment.ShipTo.Address.PostalCode = ship_to.zip or ''
        shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''
        if ship_to.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''
        # shipment.ShipTo.Phone.Number = ship_to.phone or ''
        if not ship_to.commercial_partner_id.is_company:
            shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()

        shipment.Service.Code = service_type or ''
        shipment.Service.Description = 'Service Code'
        if service_type == "96":
            shipment.NumOfPieces = int(shipment_info.get('total_qty'))
        shipment.ShipmentServiceOptions = ''
        shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = 1

        try:
            # Get rate using for provided detail
            response = client.service.ProcessRate(
                Request=request,
                CustomerClassification=classification,
                Shipment=shipment)

            # Check if ProcessRate is not success then return reason for that
            if response.Response.ResponseStatus.Code != "1":
                return self.get_error_message(
                    response.Response.ResponseStatus.Code,
                    response.Response.ResponseStatus.Description)

            result = {}
            result['currency_code'] = response.RatedShipment[
                0].TotalCharges.CurrencyCode

            # Some users are qualified to receive negotiated rates
            negotiated_rate = 'NegotiatedRateCharges' in response.RatedShipment[
                0] and response.RatedShipment[
                    0].NegotiatedRateCharges.TotalCharge.MonetaryValue or None

            result['price'] = negotiated_rate or response.RatedShipment[
                0].TotalCharges.MonetaryValue
            return result

        except suds.WebFault as e:
            # childAtPath behaviour is changing at version 0.6
            prefix = ''
            if SUDS_VERSION >= "0.6":
                prefix = '/Envelope/Body/Fault'
            return self.get_error_message(
                e.document.childAtPath(
                    prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code'
                ).getText(),
                e.document.childAtPath(
                    prefix +
                    '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').
                getText())
        except URLError as e:
            return self.get_error_message('0', 'UPS Server Not Found:\n%s' % e)
Exemple #30
0
        print '\nreply(\n%s\n)\n' % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
    except Exception, e:
        errors += 1
        print e
        tb.print_exc()

    try:
        print "echo('this is cool')"
        result = client.service.echo('this is cool')
        print '\nreply( %s )\n' % str(result)
        print 'echo(None)'
        result = client.service.echo(null())
        print '\nreply( %s )\n' % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
    except Exception, e:
        errors += 1
        print e
        tb.print_exc()

    try:
        print 'hello()'
        result = client.service.hello()
        print '\nreply( %s )\n' % str(result)
    except WebFault, f:
Exemple #31
0
 def test_null(self):
     self.assertEqual(
         self.service.add_floats(null(), null()), 0)
 def test_null_args(self):
     res = self.service.add_integer_dicts(null(), null())
     self.assertEqual(res.a, 0)
     self.assertEqual(res.b, 0)
Exemple #33
0
 def test_null_args(self):
     res = self.service.add_string_dicts(null(), null())
     self.assertEqual(res.a, None)
     self.assertEqual(res.b, None)
Exemple #34
0
        print "\nreply(\n%s\n)\n" % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
    except Exception, e:
        errors += 1
        print e
        tb.print_exc()

    try:
        print "echo('this is cool')"
        result = client.service.echo("this is cool")
        print "\nreply( %s )\n" % str(result)
        print "echo(None)"
        result = client.service.echo(null())
        print "\nreply( %s )\n" % str(result)
    except WebFault, f:
        errors += 1
        print f
        print f.fault
    except Exception, e:
        errors += 1
        print e
        tb.print_exc()

    try:
        print "hello()"
        result = client.service.hello()
        print "\nreply( %s )\n" % str(result)
    except WebFault, f:
Exemple #35
0
    def change_responsible(self, fqdn, name, firstname=None):
        logging.debug("Getting object representation...")
        hostname = shortify(fqdn)
        try:
            device = self.client.service.getDeviceInfo(hostname)
        except WebFault, error:
            logging.debug(error)
            raise AiToolsLandbError("getDeviceInfo failed (%s)" % error)

        new_responsible = self.client.factory.create("types:PersonInput")
        if not firstname:
            new_responsible.FirstName = 'E-GROUP'
        else:
            new_responsible.FirstName = firstname.upper()
        new_responsible.Name = name.upper()
        new_responsible.Department = null()
        new_responsible.Group = null()

        logging.debug("Current responsible: %s", device.ResponsiblePerson)
        logging.debug("New responsible: %s", new_responsible)
        device.ResponsiblePerson = new_responsible

        if self.dryrun:
            logging.info("Would have changed the responsible to '%s'", name)
            return

        logging.debug("Calling deviceUpdate...")
        try:
            self.client.service.deviceUpdate(hostname, device)
        except WebFault, error:
            logging.debug(error)
Exemple #36
0
 def test_null(self):
     self.assertEqual(self.service.add_simple(null(), null()), None)
Exemple #37
0
 def test_null(self):
     self.assertEqual(
         self.service.add_simple(null(), null()), None)
Exemple #38
0
    def send_shipping(self,
                      shipment_info,
                      packages,
                      shipper,
                      ship_from,
                      ship_to,
                      packaging_type,
                      service_type,
                      label_file_type='GIF'):

        client = self._set_client(self.ship_wsdl, 'Ship', 'ShipmentRequest')

        request = client.factory.create('ns0:RequestType')
        request.RequestOption = 'nonvalidate'

        namespace = 'ns3'
        label = client.factory.create(
            '{}:LabelSpecificationType'.format(namespace))

        label.LabelImageFormat.Code = label_file_type
        label.LabelImageFormat.Description = label_file_type
        if label_file_type != 'GIF':
            label.LabelStockSize.Height = '6'
            label.LabelStockSize.Width = '4'

        shipment = client.factory.create('{}:ShipmentType'.format(namespace))
        shipment.Description = shipment_info.get('description')

        for package in self.set_package_detail(client, packages,
                                               packaging_type, namespace,
                                               ship_from, ship_to):
            shipment.Package.append(package)

        shipment.Shipper.AttentionName = shipper.name or ''
        shipment.Shipper.Name = shipper.parent_id.name or shipper.name or ''
        shipment.Shipper.Address.AddressLine = [
            l for l in [shipper.street or '', shipper.street2 or ''] if l
        ]
        shipment.Shipper.Address.City = shipper.city or ''
        shipment.Shipper.Address.PostalCode = shipper.zip or ''
        shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''
        if shipper.country_id.code in ('US', 'CA', 'IE'):
            shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''
        shipment.Shipper.ShipperNumber = self.shipper_number or ''
        shipment.Shipper.Phone.Number = self._clean_phone_number(shipper.phone)

        shipment.ShipFrom.AttentionName = ship_from.name or ''
        shipment.ShipFrom.Name = ship_from.parent_id.name or ship_from.name or ''
        shipment.ShipFrom.Address.AddressLine = [
            l for l in [ship_from.street or '', ship_from.street2 or ''] if l
        ]
        shipment.ShipFrom.Address.City = ship_from.city or ''
        shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''
        shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''
        if ship_from.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''
        shipment.ShipFrom.Phone.Number = self._clean_phone_number(
            ship_from.phone)

        shipment.ShipTo.AttentionName = ship_to.name or ''
        shipment.ShipTo.Name = ship_to.parent_id.name or ship_to.name or ''
        shipment.ShipTo.Address.AddressLine = [
            l for l in [ship_to.street or '', ship_to.street2 or ''] if l
        ]
        shipment.ShipTo.Address.City = ship_to.city or ''
        shipment.ShipTo.Address.PostalCode = ship_to.zip or ''
        shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''
        if ship_to.country_id.code in ('US', 'CA', 'IE'):
            shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''
        shipment.ShipTo.Phone.Number = self._clean_phone_number(ship_to.phone)
        if not ship_to.commercial_partner_id.is_company:
            shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()

        shipment.Service.Code = service_type or ''
        shipment.Service.Description = 'Service Code'
        if service_type == "96":
            shipment.NumOfPiecesInShipment = int(
                shipment_info.get('total_qty'))
        shipment.ShipmentServiceOptions = ''
        shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = 1

        # Shipments from US to CA or PR require extra info
        if ship_from.country_id.code == 'US' and ship_to.country_id.code in [
                'CA', 'PR'
        ]:
            shipment.InvoiceLineTotal.CurrencyCode = shipment_info.get(
                'itl_currency_code')
            shipment.InvoiceLineTotal.MonetaryValue = shipment_info.get(
                'ilt_monetary_value')

        # set the default method for payment using shipper account
        payment_info = client.factory.create('ns3:PaymentInformation')
        shipcharge = client.factory.create('ns3:ShipmentCharge')
        shipcharge.Type = '01'
        shipcharge.BillShipper.AccountNumber = self.shipper_number or ''
        payment_info.ShipmentCharge = shipcharge
        shipment.PaymentInformation = payment_info

        try:
            response = client.service.ProcessShipment(Request=request,
                                                      Shipment=shipment,
                                                      LabelSpecification=label)

            # Check if shipment is not success then return reason for that
            if response.Response.ResponseStatus.Code != "1":
                return self.get_error_message(
                    response.Response.ResponseStatus.Code,
                    response.Response.ResponseStatus.Description)

            result = {}
            result['label_binary_data'] = {}
            for package in response.ShipmentResults.PackageResults:
                result['label_binary_data'][
                    package.TrackingNumber] = self.save_label(
                        package.ShippingLabel.GraphicImage,
                        label_file_type=label_file_type)
            result[
                'tracking_ref'] = response.ShipmentResults.ShipmentIdentificationNumber
            result[
                'currency_code'] = response.ShipmentResults.ShipmentCharges.TotalCharges.CurrencyCode

            # Some users are qualified to receive negotiated rates
            negotiated_rate = 'NegotiatedRateCharges' in response.ShipmentResults and response.ShipmentResults.NegotiatedRateCharges.TotalCharge.MonetaryValue or None

            result[
                'price'] = negotiated_rate or response.ShipmentResults.ShipmentCharges.TotalCharges.MonetaryValue
            return result

        except suds.WebFault as e:
            # childAtPath behaviour is changing at version 0.6
            prefix = ''
            if SUDS_VERSION >= "0.6":
                prefix = '/Envelope/Body/Fault'
            return self.get_error_message(
                e.document.childAtPath(
                    prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code'
                ).getText(),
                e.document.childAtPath(
                    prefix +
                    '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').
                getText())
        except URLError as e:
            return self.get_error_message('0', 'UPS Server Not Found:\n%s' % e)
 def test_null(self):
     self.assertEqual(self.service.add_integers(null(), null()), 0)