Exemplo n.º 1
0
    def test_operation_request_and_reply(self):
        xsd_content = '<xsd:element name="Data" type="xsd:string"/>'
        web_service_URL = "Great minds think alike"
        xsd_target_namespace = "omicron psi"
        wsdl = testutils.wsdl(suds.byte_str(xsd_content), operation_name="pi",
            xsd_target_namespace=xsd_target_namespace, input="Data",
            output="Data", web_service_URL=web_service_URL)
        test_input_data = "Riff-raff"
        test_output_data = "La-di-da-da-da"
        store = MockDocumentStore(wsdl=wsdl)
        transport = MockTransport(send_data=suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <Data xmlns="%s">%s</Data>
  </env:Body>
</env:Envelope>""" % (xsd_target_namespace, test_output_data)))
        client = suds.client.Client("suds://wsdl", documentStore=store,
            cache=None, transport=transport)
        assert transport.mock_log == []
        reply = client.service.pi(test_input_data)
        assert len(transport.mock_log) == 1
        assert transport.mock_log[0][0] == "send"
        assert transport.mock_log[0][1][0] == web_service_URL
        request_message = transport.mock_log[0][1][1]
        assert suds.byte_str(xsd_target_namespace) in request_message
        assert suds.byte_str(test_input_data) in request_message
        assert reply == test_output_data
def test_accessing_DocumentStore_content():
    content1 = suds.byte_str("one")
    content2 = suds.byte_str("two")
    content1_1 = suds.byte_str("one one")

    store = suds.store.DocumentStore({"1":content1})
    assert len(store) == 2
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)

    store = suds.store.DocumentStore({"1":content1, "2":content2})
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)
    __test_open(store, "2", content2)

    store = suds.store.DocumentStore(uno=content1, due=content2)
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "uno", content1)
    __test_open(store, "due", content2)

    store = suds.store.DocumentStore({"1 1":content1_1})
    assert len(store) == 2
    __test_default_DocumentStore_content(store)
    __test_open(store, "1 1", content1_1)

    store = suds.store.DocumentStore({"1":content1, "1 1":content1_1})
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)
    __test_open(store, "1 1", content1_1)
def test_DocumentCache(tmpdir):
    cacheFolder = tmpdir.join("puffy").strpath
    cache = suds.cache.DocumentCache(cacheFolder)
    assert isinstance(cache, suds.cache.FileCache)
    assert cache.get("unga1") is None

    # TODO: DocumentCache class interface seems silly. Its get() operation
    # returns an XML document while its put() operation takes an XML element.
    # The put() operation also silently ignores passed data of incorrect type.
    # TODO: Update this test to no longer depend on the exact input XML data
    # formatting. We currently expect it to be formatted exactly as what gets
    # read back from the DocumentCache.
    content = suds.byte_str("""\
<xsd:element name="Elemento">
   <xsd:simpleType>
      <xsd:restriction base="xsd:string">
         <xsd:enumeration value="alfa"/>
         <xsd:enumeration value="beta"/>
         <xsd:enumeration value="gamma"/>
      </xsd:restriction>
   </xsd:simpleType>
</xsd:element>""")
    xml = suds.sax.parser.Parser().parse(suds.BytesIO(content))
    cache.put("unga1", xml.getChildren()[0])
    readXML = cache.get("unga1")
    assert isinstance(readXML, suds.sax.document.Document)
    readXMLElements = readXML.getChildren()
    assert len(readXMLElements) == 1
    readXMLElement = readXMLElements[0]
    assert isinstance(readXMLElement, suds.sax.element.Element)
    assert suds.byte_str(str(readXMLElement)) == content
def test_accessing_DocumentStore_content():
    content1 = suds.byte_str("one")
    content2 = suds.byte_str("two")
    content1_1 = suds.byte_str("one one")

    store = suds.store.DocumentStore({"1": content1})
    assert len(store) == 2
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)

    store = suds.store.DocumentStore({"1": content1, "2": content2})
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)
    __test_open(store, "2", content2)

    store = suds.store.DocumentStore(uno=content1, due=content2)
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "uno", content1)
    __test_open(store, "due", content2)

    store = suds.store.DocumentStore({"1 1": content1_1})
    assert len(store) == 2
    __test_default_DocumentStore_content(store)
    __test_open(store, "1 1", content1_1)

    store = suds.store.DocumentStore({"1": content1, "1 1": content1_1})
    assert len(store) == 3
    __test_default_DocumentStore_content(store)
    __test_open(store, "1", content1)
    __test_open(store, "1 1", content1_1)
Exemplo n.º 5
0
 def test_imported_WSDL_transport(self, url):
     wsdl_import_wrapper = wsdl_import_wrapper_format % (url,)
     wsdl_imported = suds.byte_str(wsdl_imported_format % ("",))
     store = MockDocumentStore(wsdl=suds.byte_str(wsdl_import_wrapper))
     t = MockTransport(open_data=wsdl_imported)
     suds.client.Client("suds://wsdl", cache=None, documentStore=store, transport=t)
     assert t.mock_log == [("open", [url])]
    def open(self, request):
        if "?wsdl" in request.url:
            return suds.BytesIO(suds.byte_str(WSDL))
        elif "?xsd" in request.url:
            return suds.BytesIO(suds.byte_str(XSD))

        pytest.fail("No supported open request url: {}".format(request.url))
Exemplo n.º 7
0
def test_DocumentCache(tmpdir):
    cacheFolder = tmpdir.join("puffy").strpath
    cache = suds.cache.DocumentCache(cacheFolder)
    assert isinstance(cache, suds.cache.FileCache)
    assert cache.get("unga1") is None

    # TODO: DocumentCache class interface seems silly. Its get() operation
    # returns an XML document while its put() operation takes an XML element.
    # The put() operation also silently ignores passed data of incorrect type.
    # TODO: Update this test to no longer depend on the exact input XML data
    # formatting. We currently expect it to be formatted exactly as what gets
    # read back from the DocumentCache.
    content = suds.byte_str("""\
<xsd:element name="Elemento">
   <xsd:simpleType>
      <xsd:restriction base="xsd:string">
         <xsd:enumeration value="alfa"/>
         <xsd:enumeration value="beta"/>
         <xsd:enumeration value="gamma"/>
      </xsd:restriction>
   </xsd:simpleType>
</xsd:element>""")
    xml = suds.sax.parser.Parser().parse(suds.BytesIO(content))
    cache.put("unga1", xml.getChildren()[0])
    readXML = cache.get("unga1")
    assert isinstance(readXML, suds.sax.document.Document)
    readXMLElements = readXML.getChildren()
    assert len(readXMLElements) == 1
    readXMLElement = readXMLElements[0]
    assert isinstance(readXMLElement, suds.sax.element.Element)
    assert suds.byte_str(str(readXMLElement)) == content
Exemplo n.º 8
0
        def test_avoid_external_XSD_fetching(self):
            # Prepare document content.
            xsd_target_namespace = "balancana"
            wsdl = tests.wsdl("""\
              <xsd:import schemaLocation="suds://imported_xsd"/>
              <xsd:include schemaLocation="suds://included_xsd"/>""",
                xsd_target_namespace=xsd_target_namespace)
            external_xsd_format = """\
<?xml version='1.0' encoding='UTF-8'?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
    <element name="external%d" type="string"/>
</schema>"""
            external_xsd1 = suds.byte_str(external_xsd_format % (1,))
            external_xsd2 = suds.byte_str(external_xsd_format % (2,))

            # Add to cache.
            cache = MockCache()
            store1 = MockDocumentStore(wsdl=wsdl, imported_xsd=external_xsd1,
                included_xsd=external_xsd2)
            c1 = suds.client.Client("suds://wsdl", cachingpolicy=1,
                cache=cache, documentStore=store1, transport=MockTransport())
            assert store1.mock_log == ["suds://wsdl", "suds://imported_xsd",
                "suds://included_xsd"]
            assert len(cache.mock_data) == 1
            wsdl_object_id, wsdl_object = cache.mock_data.items()[0]
            assert wsdl_object.__class__ is suds.wsdl.Definitions

            # Reuse from cache.
            cache.mock_operation_log = []
            store2 = MockDocumentStore(wsdl=wsdl)
            c2 = suds.client.Client("suds://wsdl", cachingpolicy=1,
                cache=cache, documentStore=store2, transport=MockTransport())
            assert cache.mock_operation_log == [("get", [wsdl_object_id])]
            assert store2.mock_log == []
Exemplo n.º 9
0
        def test_avoid_imported_WSDL_fetching(self):
            # Prepare data.
            url_imported = "suds://wsdl_imported"
            wsdl_import_wrapper = wsdl_import_wrapper_format % (url_imported,)
            wsdl_import_wrapper = suds.byte_str(wsdl_import_wrapper)
            wsdl_imported = suds.byte_str(wsdl_imported_format % ("",))

            # Add to cache.
            cache = MockCache()
            store1 = MockDocumentStore(wsdl=wsdl_import_wrapper,
                wsdl_imported=wsdl_imported)
            c1 = suds.client.Client("suds://wsdl", cachingpolicy=1,
                cache=cache, documentStore=store1, transport=MockTransport())
            assert store1.mock_log == ["suds://wsdl", "suds://wsdl_imported"]
            assert len(cache.mock_data) == 1
            wsdl_object_id, wsdl_object = cache.mock_data.items()[0]
            assert wsdl_object.__class__ is suds.wsdl.Definitions

            # Reuse from cache.
            cache.mock_operation_log = []
            store2 = MockDocumentStore(wsdl=wsdl_import_wrapper)
            c2 = suds.client.Client("suds://wsdl", cachingpolicy=1,
                cache=cache, documentStore=store2, transport=MockTransport())
            assert cache.mock_operation_log == [("get", [wsdl_object_id])]
            assert store2.mock_log == []
Exemplo n.º 10
0
 def test_imported_WSDL_transport(self, url):
     wsdl_import_wrapper = wsdl_import_wrapper_format % (url,)
     wsdl_imported = suds.byte_str(wsdl_imported_format % ("",))
     store = MockDocumentStore(wsdl=suds.byte_str(wsdl_import_wrapper))
     t = MockTransport(open_data=wsdl_imported)
     suds.client.Client("suds://wsdl", cache=None, documentStore=store,
         transport=t)
     assert t.mock_operation_log == [("open", url)]
Exemplo n.º 11
0
def test_wrapped_sequence_output():
    client = testutils.lxmlclient_from_wsdl(testutils.wsdl("""\
      <xsd:element name="Wrapper">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="result1" type="xsd:string"/>
            <xsd:element name="result2" type="xsd:string"/>
            <xsd:element name="result3" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>""", output="Wrapper"))

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Wrapper xmlns="my-namespace">
        <result1>Uno</result1>
        <result2>Due</result2>
        <result3>Tre</result3>
    </Wrapper>
  </Body>
</Envelope>""")))

    # Check response content.
    assert len(response) == 3
    assert response.result1 == "Uno"
    assert response.result2 == "Due"
    assert response.result3 == "Tre"
    assert_lxml_string_value(response.result1)
    assert_lxml_string_value(response.result2)
    assert_lxml_string_value(response.result3)
    
    client = testutils.lxmlclient_from_wsdl(testutils.wsdl("""\
      <xsd:element name="Wrapper">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="result1" type="xsd:string"/>
            <xsd:element name="result2" type="xsd:string"/>
            <xsd:element name="result3" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>""", output="Wrapper"))

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Wrapper xmlns="my-namespace">
    </Wrapper>
  </Body>
</Envelope>""")))

    # Check response content.
    assert len(response) == 3
    assert response.result1 is None
    assert response.result2 is None
    assert response.result3 is None
Exemplo n.º 12
0
    def test_string_representation_with_no_message(self):
        url = "look at my silly little URL"
        headers = {suds.byte_str("yuck"): suds.byte_str("ptooiii...")}
        request = Request(url)
        request.headers = headers
        expected = u("""\
URL: %s
HEADERS: %s""") % (url, request.headers)
        assert text_type(request) == expected
        if sys.version_info < (3, ):
            assert str(request) == expected.encode("utf-8")
Exemplo n.º 13
0
    def test_string_representation_with_no_message(self):
        url = "look at my silly little URL"
        headers = {suds.byte_str("yuck"): suds.byte_str("ptooiii...")}
        request = Request(url)
        request.headers = headers
        expected = u("""\
URL: %s
HEADERS: %s""") % (url, request.headers)
        assert text_type(request) == expected
        if sys.version_info < (3,):
            assert str(request) == expected.encode("utf-8")
Exemplo n.º 14
0
def test_invalid_fault_namespace(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    fault_xml = suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:p="x">
  <env:Body>
    <p:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>Dummy error.</faultstring>
      <detail>
        <errorcode>ultimate</errorcode>
      </detail>
    </p:Fault>
  </env:Body>
</env:Envelope>
""")
    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=False)
    inject = dict(reply=fault_xml, status=http_client.OK)
    e = pytest.raises(Exception, client.service.f, __inject=inject).value
    try:
        assert e.__class__ is Exception
        assert str(e) == "<faultcode/> not mapped to message part"
    finally:
        del e  # explicitly break circular reference chain in Python 3

    for http_status in (http_client.INTERNAL_SERVER_ERROR,
        http_client.PAYMENT_REQUIRED):
        status, reason = client.service.f(__inject=dict(reply=fault_xml,
            status=http_status, description="trla baba lan"))
        assert status == http_status
        assert reason == "trla baba lan"
Exemplo n.º 15
0
def test_fault_reply_with_unicode_faultstring(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    unicode_string = u("\\u20AC Jurko Gospodneti\\u0107 "
        "\\u010C\\u0106\\u017D\\u0160\\u0110"
        "\\u010D\\u0107\\u017E\\u0161\\u0111")
    fault_xml = suds.byte_str(u("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <env:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>%s</faultstring>
    </env:Fault>
  </env:Body>
</env:Envelope>
""") % (unicode_string,))

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=True)
    inject = dict(reply=fault_xml, status=http_client.INTERNAL_SERVER_ERROR)
    e = pytest.raises(suds.WebFault, client.service.f, __inject=inject).value
    try:
        assert e.fault.faultstring == unicode_string
        assert e.document.__class__ is suds.sax.document.Document
    finally:
        del e  # explicitly break circular reference chain in Python 3

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=False)
    status, fault = client.service.f(__inject=dict(reply=fault_xml,
        status=http_client.INTERNAL_SERVER_ERROR))
    assert status == http_client.INTERNAL_SERVER_ERROR
    assert fault.faultstring == unicode_string
Exemplo n.º 16
0
def test_disabling_automated_simple_interface_unwrapping():
    client = testutils.client_from_wsdl(testutils.wsdl("""\
      <xsd:element name="Wrapper">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="Elemento" type="xsd:string"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>""", output="Wrapper"), unwrap=False)
    assert not _isOutputWrapped(client, "f")

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Wrapper xmlns="my-namespace">
        <Elemento>La-di-da-da-da</Elemento>
    </Wrapper>
  </Body>
</Envelope>""")))

    assert response.__class__.__name__ == "Wrapper"
    assert len(response.__class__.__bases__) == 1
    assert response.__class__.__bases__[0] is suds.sudsobject.Object
    assert response.Elemento.__class__ is suds.sax.text.Text
    assert response.Elemento == "La-di-da-da-da"
Exemplo n.º 17
0
 def _call(self, service, port, expect_fault, name, *args):
     client = self._client()
     self._backup_options()
     if service or (service == 0):
         client.set_options(service=parse_index(service))
     if port or (port == 0):
         client.set_options(port=parse_index(port))
     method = getattr(client.service, name)
     received = None
     try:
         if len(args) == 1 and isinstance(args[0], RawSoapMessage):
             message = byte_str(args[0].message)
             received = method(__inject={'msg': message})
         else:
             received = method(*args)
         if expect_fault:
             raise AssertionError('The server did not raise a fault.')
     except WebFault as e:
         if not expect_fault:
             raise e
         received = e.fault
     finally:
         self._restore_options()
     return_xml = self._get_external_option("return_xml", False)
     if return_xml:
         received = self.get_last_received()
     return received
Exemplo n.º 18
0
def test_sending_py2_bytes_location(urlString, expectedException):
    """

    Suds should accept single-byte string URL values under Python 2, but should

    still report an error if those strings contain any non-ASCII characters.



    """
    class MockURLOpener:
        def open(self, request, timeout=None):

            raise MyException

    transport = suds.transport.http.HttpTransport()

    transport.urlopener = MockURLOpener()

    store = suds.store.DocumentStore(wsdl=_wsdl_with_no_input_data("http://x"))

    client = suds.client.Client("suds://wsdl",
                                cache=None,
                                documentStore=store,
                                transport=transport)

    client.options.location = suds.byte_str(urlString)

    pytest.raises(expectedException, client.service.f)
Exemplo n.º 19
0
def test_enum():
    client = testutils.lxmlclient_from_wsdl(testutils.wsdl("""\
      <xsd:element name="Wrapper">
        <xsd:element name="Size">
          <xsd:simpleType name="DataSize">
            <xsd:restriction base="xsd:string">
              <xsd:enumeration value="1" />
              <xsd:enumeration value="2"/>
              <xsd:enumeration value="3"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
      </xsd:element>""", output="Wrapper"))

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Wrapper xmlns="my-namespace">
        <DataSize>1</DataSize>
    </Wrapper>
  </Body>
</Envelope>""")))

    # Check response content.
    assert len(response) == 1
    assert response.size == 1
Exemplo n.º 20
0
    def construct_XML(element_name="Elemento"):
        """
        Construct XML content and an Element wrapping it.

        Constructed content may be parametrized with the given element name.

        """
        # TODO: Update the tests in this group to no longer depend on the exact
        # input XML data formatting. They currently expect it to be formatted
        # exactly as what gets read back from their DocumentCache.
        content = suds.byte_str("""\
<xsd:element name="%s">
   <xsd:simpleType>
      <xsd:restriction base="xsd:string">
         <xsd:enumeration value="alfa"/>
         <xsd:enumeration value="beta"/>
         <xsd:enumeration value="gamma"/>
      </xsd:restriction>
   </xsd:simpleType>
</xsd:element>""" % (element_name, ))
        xml = suds.sax.parser.Parser().parse(suds.BytesIO(content))
        children = xml.getChildren()
        assert len(children) == 1
        assert children[0].__class__ is suds.sax.element.Element
        return content, children[0]
Exemplo n.º 21
0
def test_fault_reply_with_unicode_faultstring(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    unicode_string = u("\u20AC Jurko Gospodneti\u0107 "
        "\u010C\u0106\u017D\u0160\u0110"
        "\u010D\u0107\u017E\u0161\u0111")
    fault_xml = suds.byte_str(u("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <env:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>%s</faultstring>
    </env:Fault>
  </env:Body>
</env:Envelope>
""") % (unicode_string,))

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=True)
    inject = dict(reply=fault_xml, status=http_client.INTERNAL_SERVER_ERROR)
    e = pytest.raises(suds.WebFault, client.service.f, __inject=inject).value
    try:
        assert e.fault.faultstring == unicode_string
        assert e.document.__class__ is suds.sax.document.Document
    finally:
        del e  # explicitly break circular reference chain in Python 3

    client = testutils.client_from_wsdl(_wsdl__simple_f, faults=False)
    status, fault = client.service.f(__inject=dict(reply=fault_xml,
        status=http_client.INTERNAL_SERVER_ERROR))
    assert status == http_client.INTERNAL_SERVER_ERROR
    assert fault.faultstring == unicode_string
Exemplo n.º 22
0
def _wsdl_with_no_input_data(url):
    """
    Return a WSDL schema with a single operation f taking no parameters.

    Included operation returns no values. Externally specified URL is used as
    the web service location.

    """
    return suds.byte_str(u"""\
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions targetNamespace="myNamespace"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
  xmlns:tns="myNamespace"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <wsdl:portType name="Port">
    <wsdl:operation name="f"/>
  </wsdl:portType>
  <wsdl:binding name="Binding" type="tns:Port">
    <soap:binding style="document"
      transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="f"/>
  </wsdl:binding>
  <wsdl:service name="Service">
    <wsdl:port name="Port" binding="tns:Binding">
      <soap:address location="%s"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>""" % (url,))
Exemplo n.º 23
0
    def construct_XML(element_name="Elemento"):
        """
        Construct XML content and an Element wrapping it.

        Constructed content may be parametrized with the given element name.

        """
        # TODO: Update the tests in this group to no longer depend on the exact
        # input XML data formatting. They currently expect it to be formatted
        # exactly as what gets read back from their DocumentCache.
        content = suds.byte_str("""\
<xsd:element name="%s">
   <xsd:simpleType>
      <xsd:restriction base="xsd:string">
         <xsd:enumeration value="alfa"/>
         <xsd:enumeration value="beta"/>
         <xsd:enumeration value="gamma"/>
      </xsd:restriction>
   </xsd:simpleType>
</xsd:element>""" % (element_name,))
        xml = suds.sax.parser.Parser().parse(suds.BytesIO(content))
        children = xml.getChildren()
        assert len(children) == 1
        assert children[0].__class__ is suds.sax.element.Element
        return content, children[0]
Exemplo n.º 24
0
def test_enum():
    client = testutils.lxmlclient_from_wsdl(
        testutils.wsdl("""\
      <xsd:element name="Wrapper">
        <xsd:element name="Size">
          <xsd:simpleType name="DataSize">
            <xsd:restriction base="xsd:string">
              <xsd:enumeration value="1" />
              <xsd:enumeration value="2"/>
              <xsd:enumeration value="3"/>
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
      </xsd:element>""",
                       output="Wrapper"))

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Wrapper xmlns="my-namespace">
        <DataSize>1</DataSize>
    </Wrapper>
  </Body>
</Envelope>""")))

    # Check response content.
    assert len(response) == 1
    assert response.size == 1
def test_SOAP_headers():
    """Rudimentary 'soapheaders' option usage test."""
    wsdl = suds.byte_str("""\
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions targetNamespace="my-target-namespace"
    xmlns:tns="my-target-namespace"
    xmlns:s="http://www.w3.org/2001/XMLSchema"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">

  <wsdl:types>
    <s:schema elementFormDefault="qualified"
        targetNamespace="my-target-namespace">
      <s:element name="MyHeader">
        <s:complexType>
          <s:sequence>
            <s:element name="Freaky" type="s:hexBinary"/>
          </s:sequence>
        </s:complexType>
      </s:element>
    </s:schema>
  </wsdl:types>

  <wsdl:message name="myOperationHeader">
    <wsdl:part name="MyHeader" element="tns:MyHeader"/>
  </wsdl:message>

  <wsdl:portType name="MyWSSOAP">
    <wsdl:operation name="my_operation"/>
  </wsdl:portType>

  <wsdl:binding name="MyWSSOAP" type="tns:MyWSSOAP">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="my_operation">
      <soap:operation soapAction="my-SOAP-action" style="document"/>
      <wsdl:input>
        <soap:header message="tns:myOperationHeader" part="MyHeader"
            use="literal"/>
      </wsdl:input>
    </wsdl:operation>
  </wsdl:binding>

  <wsdl:service name="MyWS">
    <wsdl:port name="MyWSSOAP" binding="tns:MyWSSOAP">
      <soap:address location="protocol://my-WS-URL"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
""")
    header_data = "fools rush in where angels fear to tread"
    client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
    client.options.soapheaders = header_data
    _assert_request_content(client.service.my_operation(), """\
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Header>
    <MyHeader xmlns="my-target-namespace">%s</MyHeader>
  </Header>
  <Body/>
</Envelope>""" % (header_data,))
def test_fault_reply_with_unicode_faultstring(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    unicode_string = "€ Jurko Gospodnetić ČĆŽŠĐčćžšđ"
    fault_xml = suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <env:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>%s</faultstring>
    </env:Fault>
  </env:Body>
</env:Envelope>
""" % unicode_string)

    client = tests.client_from_wsdl(_wsdl__simple, faults=True)
    inject = dict(reply=fault_xml, status=http.client.INTERNAL_SERVER_ERROR)
    e = pytest.raises(suds.WebFault, client.service.f, __inject=inject).value
    assert e.fault.faultstring == unicode_string
    assert e.document.__class__ is suds.sax.document.Document

    client = tests.client_from_wsdl(_wsdl__simple, faults=False)
    status, fault = client.service.f(__inject=dict(reply=fault_xml,
        status=http.client.INTERNAL_SERVER_ERROR))
    assert status == http.client.INTERNAL_SERVER_ERROR
    assert fault.faultstring == unicode_string
Exemplo n.º 27
0
def test_SOAP_headers():
    """Rudimentary 'soapheaders' option usage test."""
    wsdl = suds.byte_str("""\
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions targetNamespace="my-target-namespace"
    xmlns:tns="my-target-namespace"
    xmlns:s="http://www.w3.org/2001/XMLSchema"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">

  <wsdl:types>
    <s:schema elementFormDefault="qualified"
        targetNamespace="my-target-namespace">
      <s:element name="MyHeader">
        <s:complexType>
          <s:sequence>
            <s:element name="Freaky" type="s:hexBinary"/>
          </s:sequence>
        </s:complexType>
      </s:element>
    </s:schema>
  </wsdl:types>

  <wsdl:message name="myOperationHeader">
    <wsdl:part name="MyHeader" element="tns:MyHeader"/>
  </wsdl:message>

  <wsdl:portType name="MyWSSOAP">
    <wsdl:operation name="my_operation"/>
  </wsdl:portType>

  <wsdl:binding name="MyWSSOAP" type="tns:MyWSSOAP">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="my_operation">
      <soap:operation soapAction="my-SOAP-action" style="document"/>
      <wsdl:input>
        <soap:header message="tns:myOperationHeader" part="MyHeader"
            use="literal"/>
      </wsdl:input>
    </wsdl:operation>
  </wsdl:binding>

  <wsdl:service name="MyWS">
    <wsdl:port name="MyWSSOAP" binding="tns:MyWSSOAP">
      <soap:address location="protocol://my-WS-URL"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
""")
    header_data = "fools rush in where angels fear to tread"
    client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
    client.options.soapheaders = header_data
    _assert_request_content(client.service.my_operation(), """\
<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Header>
    <MyHeader xmlns="my-target-namespace">%s</MyHeader>
  </Header>
  <Body/>
</Envelope>""" % (header_data,))
def test_invalid_fault_namespace(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    fault_xml = suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:p="x">
  <env:Body>
    <p:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>Dummy error.</faultstring>
      <detail>
        <errorcode>ultimate</errorcode>
      </detail>
    </p:Fault>
  </env:Body>
</env:Envelope>
""")
    client = tests.client_from_wsdl(_wsdl__simple, faults=False)
    inject = dict(reply=fault_xml, status=http.client.OK)
    e = pytest.raises(Exception, client.service.f, __inject=inject).value
    assert e.__class__ is Exception
    assert str(e) == "<faultcode/> not mapped to message part"

    for http_status in (http.client.INTERNAL_SERVER_ERROR,
        http.client.PAYMENT_REQUIRED):
        status, reason = client.service.f(__inject=dict(reply=fault_xml,
            status=http_status, description="trla baba lan"))
        assert status == http_status
        assert reason == "trla baba lan"
def test_disabling_automated_simple_interface_unwrapping():
    client = tests.client_from_wsdl(tests.wsdl_output("""\
      <xsd:element name="Wrapper">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="Elemento" type="xsd:string" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>""", "Wrapper"), unwrap=False)
    assert not _isOutputWrapped(client, "f")

    response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <Wrapper xmlns="my-namespace">
        <Elemento>La-di-da-da-da</Elemento>
    </Wrapper>
  </env:Body>
</env:Envelope>""")))

    assert response.__class__.__name__ == "Wrapper"
    assert len(response.__class__.__bases__) == 1
    assert response.__class__.__bases__[0] is suds.sudsobject.Object
    assert response.Elemento.__class__ is suds.sax.text.Text
    assert response.Elemento == "La-di-da-da-da"
def test_fault_reply_with_unicode_faultstring(monkeypatch):
    monkeypatch.delitem(locals(), "e", False)

    unicode_string = "€ Jurko Gospodnetić ČĆŽŠĐčćžšđ"
    fault_xml = suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <env:Fault>
      <faultcode>env:Client</faultcode>
      <faultstring>%s</faultstring>
    </env:Fault>
  </env:Body>
</env:Envelope>
""" % unicode_string)

    client = tests.client_from_wsdl(_wsdl__simple, faults=True)
    inject = dict(reply=fault_xml, status=http.client.INTERNAL_SERVER_ERROR)
    e = pytest.raises(suds.WebFault, client.service.f, __inject=inject).value
    assert e.fault.faultstring == unicode_string
    assert e.document.__class__ is suds.sax.document.Document

    client = tests.client_from_wsdl(_wsdl__simple, faults=False)
    status, fault = client.service.f(__inject=dict(reply=fault_xml,
        status=http.client.INTERNAL_SERVER_ERROR))
    assert status == http.client.INTERNAL_SERVER_ERROR
    assert fault.faultstring == unicode_string
Exemplo n.º 31
0
def test_missing_wrapper_response():
    """
    Suds library's automatic structure unwrapping should not be applied to
    interpreting received SOAP Response XML.

    """
    client = tests.client_from_wsdl(
        tests.wsdl_output(
            """\
      <xsd:element name="Wrapper">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element name="fResponse" type="xsd:string" />
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>""", "Wrapper"))
    assert _isOutputWrapped(client, "f")

    response_with_missing_wrapper = client.service.f(__inject=dict(
        reply=suds.byte_str("""<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <fResponse xmlns="my-namespace">Anything</fResponse>
  </env:Body>
</env:Envelope>""")))
    assert response_with_missing_wrapper is None
Exemplo n.º 32
0
def _wsdl_with_no_input_data(url):
    """
    Return a WSDL schema with a single operation f taking no parameters.

    Included operation returns no values. Externally specified URL is used as
    the web service location.

    """
    return suds.byte_str(u"""\
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions targetNamespace="myNamespace"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
  xmlns:tns="myNamespace"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <wsdl:portType name="Port">
    <wsdl:operation name="f"/>
  </wsdl:portType>
  <wsdl:binding name="Binding" type="tns:Port">
    <soap:binding style="document"
      transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="f"/>
  </wsdl:binding>
  <wsdl:service name="Service">
    <wsdl:port name="Port" binding="tns:Binding">
      <soap:address location="%s"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>""" % (url, ))
Exemplo n.º 33
0
 def compare_document_to_content(self, document, content):
     """Assert that the given XML document and content match."""
     assert document.__class__ is suds.sax.document.Document
     elements = document.getChildren()
     assert len(elements) == 1
     element = elements[0]
     assert element.__class__ is suds.sax.element.Element
     assert suds.byte_str(str(element)) == content
Exemplo n.º 34
0
 def compare_document_to_content(self, document, content):
     """Assert that the given XML document and content match."""
     assert document.__class__ is suds.sax.document.Document
     elements = document.getChildren()
     assert len(elements) == 1
     element = elements[0]
     assert element.__class__ is suds.sax.element.Element
     assert suds.byte_str(str(element)) == content
Exemplo n.º 35
0
        def __init__(self, expectedHost, expectedPort):

            self.expectedHost = expectedHost

            self.expectedPort = expectedPort

            self.sentData = suds.byte_str()

            self.hostAddress = object()
Exemplo n.º 36
0
def test_restriction_data_types():
    client_unnamed = tests.client_from_wsdl(
        tests.wsdl_output(
            """\
      <xsd:element name="Elemento">
        <xsd:simpleType>
          <xsd:restriction base="xsd:int">
            <xsd:enumeration value="1" />
            <xsd:enumeration value="3" />
            <xsd:enumeration value="5" />
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>""", "Elemento"))

    client_named = tests.client_from_wsdl(
        tests.wsdl_output(
            """\
      <xsd:simpleType name="MyType">
        <xsd:restriction base="xsd:int">
          <xsd:enumeration value="1" />
          <xsd:enumeration value="3" />
          <xsd:enumeration value="5" />
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:element name="Elemento" type="ns:MyType" />""", "Elemento"))

    client_twice_restricted = tests.client_from_wsdl(
        tests.wsdl_output(
            """\
      <xsd:simpleType name="MyTypeGeneric">
        <xsd:restriction base="xsd:int">
          <xsd:enumeration value="1" />
          <xsd:enumeration value="2" />
          <xsd:enumeration value="3" />
          <xsd:enumeration value="4" />
          <xsd:enumeration value="5" />
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:simpleType name="MyType">
        <xsd:restriction base="ns:MyTypeGeneric">
          <xsd:enumeration value="1" />
          <xsd:enumeration value="3" />
          <xsd:enumeration value="5" />
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:element name="Elemento" type="ns:MyType" />""", "Elemento"))

    for client in (client_unnamed, client_named, client_twice_restricted):
        response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <Elemento xmlns="my-namespace">5</Elemento>
  </env:Body>
</env:Envelope>""")))
        assert response.__class__ is int
        assert response == 5
Exemplo n.º 37
0
def test_badly_formed_reply_XML():

    for faults in (True, False):

        client = tests.client_from_wsdl(_wsdl__simple, faults=faults)

        pytest.raises(xml.sax.SAXParseException,
                      client.service.f,
                      __inject={"reply": suds.byte_str("bad food")})
def _unwrappable_wsdl(part_name, param_schema):
    """
    Return a WSDL schema byte string.

    The returned WSDL schema defines a single service definition with a single
    port containing a single function named 'f' taking automatically
    unwrappable input parameter using document/literal binding.

    The input parameter is defined as a single named input message part (name
    given via the 'part_name' argument) referencing an XSD schema element named
    'Wrapper' located in the 'my-namespace' namespace.

    The wrapper element's type definition (XSD schema string) is given via the
    'param_schema' argument.

    """
    return suds.byte_str(
        """\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="Wrapper">
%(param_schema)s
      </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">
    <wsdl:part name="%(part_name)s" element="ns:Wrapper" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="document" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>"""
        % {"param_schema": param_schema, "part_name": part_name}
    )
Exemplo n.º 39
0
def _encode_basic_credentials(username, password):
    """
    Encode user credentials as used in basic HTTP authentication.

    This is the value expected to be added to the 'Authorization' HTTP header.

    """
    data = suds.byte_str("%s:%s" % (username, password))
    return "Basic %s" % base64.b64encode(data).decode("utf-8")
def _unwrappable_wsdl(part_name, param_schema):
    """
    Return a WSDL schema byte string.

    The returned WSDL schema defines a single service definition with a single
    port containing a single function named 'f' taking automatically
    unwrappable input parameter using document/literal binding.

    The input parameter is defined as a single named input message part (name
    given via the 'part_name' argument) referencing an XSD schema element named
    'Wrapper' located in the 'my-namespace' namespace.

    The wrapper element's type definition (XSD schema string) is given via the
    'param_schema' argument.

    """
    return suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="Wrapper">
%(param_schema)s
      </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">
    <wsdl:part name="%(part_name)s" element="ns:Wrapper" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="document" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>""" % {
        "param_schema": param_schema,
        "part_name": part_name
    })
Exemplo n.º 41
0
def _encode_basic_credentials(username, password):
    """
    Encode user credentials as used in basic HTTP authentication.

    This is the value expected to be added to the 'Authorization' HTTP header.

    """
    data = suds.byte_str("%s:%s" % (username, password))
    return "Basic %s" % base64.b64encode(data).decode("utf-8")
def test_builtin_typed_element_parameter(part_name):
    """
    Test correctly recognizing web service operation input structure defined by
    a built-in typed element.

    """
    wsdl = suds.byte_str(
        """\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="MyElement" type="xsd:integer" />
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">
    <wsdl:part name="%s" element="ns:MyElement" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="document" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>"""
        % (part_name,)
    )
    client = tests.client_from_wsdl(wsdl, nosend=True)

    # Collect references to required WSDL model content.
    method = client.wsdl.services[0].ports[0].methods["f"]
    assert not method.soap.input.body.wrapped
    binding = method.binding.input
    assert binding.__class__ is suds.bindings.document.Document
    my_element = client.wsdl.schema.elements["MyElement", "my-namespace"]

    param_defs = binding.param_defs(method)
    _expect_params(param_defs, [("MyElement", my_element)])
def test_ACCEPTED_and_NO_CONTENT_status_reported_as_None_without_faults():
    client = tests.client_from_wsdl(_wsdl__simple, faults=False)
    f = lambda r, s : client.service.f(__inject={"reply":suds.byte_str(r),
        "status":s})
    assert f("", None) is not None
    assert f("", http.client.INTERNAL_SERVER_ERROR) is not None
    assert f("", http.client.ACCEPTED) is None
    assert f("", http.client.NO_CONTENT) is None
    assert f("bla-bla", http.client.ACCEPTED) is None
    assert f("bla-bla", http.client.NO_CONTENT) is None
def test_ACCEPTED_and_NO_CONTENT_status_reported_as_None_with_faults():
    client = tests.client_from_wsdl(_wsdl__simple, faults=True)
    f = lambda r, s : client.service.f(__inject={"reply":suds.byte_str(r),
        "status":s})
    assert f("", None) is None
    pytest.raises(Exception, f, "", http.client.INTERNAL_SERVER_ERROR)
    assert f("", http.client.ACCEPTED) is None
    assert f("", http.client.NO_CONTENT) is None
    assert f("bla-bla", http.client.ACCEPTED) is None
    assert f("bla-bla", http.client.NO_CONTENT) is None
def test_ACCEPTED_and_NO_CONTENT_status_reported_as_None_without_faults():
    client = tests.client_from_wsdl(_wsdl__simple, faults=False)
    f = lambda r, s : client.service.f(__inject={"reply":suds.byte_str(r),
        "status":s})
    assert f("", None) is not None
    assert f("", httplib.INTERNAL_SERVER_ERROR) is not None
    assert f("", httplib.ACCEPTED) is None
    assert f("", httplib.NO_CONTENT) is None
    assert f("bla-bla", httplib.ACCEPTED) is None
    assert f("bla-bla", httplib.NO_CONTENT) is None
Exemplo n.º 46
0
def test_binding_uses_argument_parsing(monkeypatch, binding_style):
    """
    Calling web service operations should use the generic argument parsing
    functionality independent of the operation's specific binding style.

    """
    class MyException(Exception):
        pass

    def raise_exception(*args, **kwargs):
        raise MyException

    monkeypatch.setattr(suds.argparser._ArgParser, "__init__", raise_exception)

    wsdl = suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="Bongo" type="xsd:string" />
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">"
    <wsdl:part name="parameters" element="ns:Bongo" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="%s" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
""" % (binding_style, ))
    client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
    pytest.raises(MyException, client.service.f)
    pytest.raises(MyException, client.service.f, "x")
    pytest.raises(MyException, client.service.f, "x", "y")
Exemplo n.º 47
0
    def test_external_XSD_transport(self, url, external_reference_tag):
        xsd_content = '<xsd:%(tag)s schemaLocation="%(url)s"/>' % dict(
            tag=external_reference_tag, url=url)
        store = MockDocumentStore(wsdl=tests.wsdl(xsd_content))
        t = MockTransport(open_data=suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"/>
"""))
        suds.client.Client("suds://wsdl", cache=None, documentStore=store,
            transport=t)
        assert t.mock_operation_log == [("open", url)]
def test_builtin_typed_element_parameter(part_name):
    """
    Test correctly recognizing web service operation input structure defined by
    a built-in typed element.

    """
    wsdl = suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="MyElement" type="xsd:integer" />
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">
    <wsdl:part name="%s" element="ns:MyElement" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="document" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>""" % (part_name, ))
    client = tests.client_from_wsdl(wsdl, nosend=True)

    # Collect references to required WSDL model content.
    method = client.wsdl.services[0].ports[0].methods["f"]
    assert not method.soap.input.body.wrapped
    binding = method.binding.input
    assert binding.__class__ is suds.bindings.document.Document
    my_element = client.wsdl.schema.elements["MyElement", "my-namespace"]

    param_defs = binding.param_defs(method)
    _expect_params(param_defs, [("MyElement", my_element)])
Exemplo n.º 49
0
def test_ACCEPTED_and_NO_CONTENT_status_reported_as_None_with_faults():
    client = tests.client_from_wsdl(_wsdl__simple, faults=True)
    f = lambda r, s: client.service.f(__inject={
        "reply": suds.byte_str(r),
        "status": s
    })
    assert f("", None) is None
    pytest.raises(Exception, f, "", httplib.INTERNAL_SERVER_ERROR)
    assert f("", httplib.ACCEPTED) is None
    assert f("", httplib.NO_CONTENT) is None
    assert f("bla-bla", httplib.ACCEPTED) is None
    assert f("bla-bla", httplib.NO_CONTENT) is None
def test_binding_uses_argument_parsing(monkeypatch, binding_style):
    """
    Calling web service operations should use the generic argument parsing
    functionality independent of the operation's specific binding style.

    """
    class MyException(Exception):
        pass
    def raise_exception(*args, **kwargs):
        raise MyException
    monkeypatch.setattr(suds.argparser._ArgParser, "__init__", raise_exception)

    wsdl = suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions targetNamespace="my-namespace"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:ns="my-namespace"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
  <wsdl:types>
    <xsd:schema targetNamespace="my-namespace"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <xsd:element name="Bongo" type="xsd:string" />
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fRequestMessage">"
    <wsdl:part name="parameters" element="ns:Bongo" />
  </wsdl:message>
  <wsdl:portType name="dummyPortType">
    <wsdl:operation name="f">
      <wsdl:input message="ns:fRequestMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="dummy" type="ns:dummyPortType">
    <soap:binding style="document"
    transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="f">
      <soap:operation soapAction="my-soap-action" style="%s" />
      <wsdl:input><soap:body use="literal" /></wsdl:input>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="dummy">
    <wsdl:port name="dummy" binding="ns:dummy">
      <soap:address location="unga-bunga-location" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
""" % (binding_style,))
    client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
    pytest.raises(MyException, client.service.f)
    pytest.raises(MyException, client.service.f, "x")
    pytest.raises(MyException, client.service.f, "x", "y")
def test_sending_unicode_location():
    """
    Suds should refuse to send HTTP requests with a target location string
    containing non-ASCII characters. URLs are supposed to consist of 
    characters only.
    
    """
    wsdl = suds.byte_str("""\
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions targetNamespace="myNamespace"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
  xmlns:tns="myNamespace"
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <wsdl:types>
    <xsd:schema targetNamespace="myNamespace">
      <xsd:element name="fRequest" type="xsd:string"/>
      <xsd:element name="fResponse" type="xsd:string"/>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="fInputMessage">
    <wsdl:part name="parameters" element="tns:fRequest"/>
  </wsdl:message>
  <wsdl:message name="fOutputMessage">
    <wsdl:part name="parameters" element="tns:fResponse"/>
  </wsdl:message>
  <wsdl:portType name="Port">
    <wsdl:operation name="f">
      <wsdl:input message="tns:fInputMessage"/>
      <wsdl:output message="tns:fOutputMessage"/>
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="Binding" type="tns:Port">
    <soap:binding style="document"
      transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="f">
      <soap:operation/>
      <wsdl:input><soap:body use="literal"/></wsdl:input>
      <wsdl:output><soap:body use="literal"/></wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="Service">
    <wsdl:port name="Port" binding="tns:Binding">
      <soap:address location="http://Дмитровский-район-152312306:9999/svc"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>""")

    store = suds.store.DocumentStore(wsdl=wsdl)
    client = suds.client.Client("suds://wsdl", cache=None, documentStore=store,
        timeout=0)
    pytest.raises(UnicodeEncodeError, client.service.f, "plonker")
Exemplo n.º 52
0
def test_WSDL_import():
    wsdl_target_namespace = "bingo-bongo"
    wsdl = testutils.wsdl("", wsdl_target_namespace=wsdl_target_namespace)
    wsdl_wrapper = suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<definitions targetNamespace="%(tns)s"
    xmlns="http://schemas.xmlsoap.org/wsdl/">
  <import namespace="%(tns)s" location="suds://wsdl"/>
</definitions>""" % {"tns": wsdl_target_namespace})
    store = suds.store.DocumentStore(wsdl=wsdl, wsdl_wrapper=wsdl_wrapper)
    client = suds.client.Client("suds://wsdl_wrapper", documentStore=store,
        cache=None, nosend=True)
    client.service.f()
Exemplo n.º 53
0
def test_restriction_data_types():
    client_unnamed = testutils.client_from_wsdl(testutils.wsdl("""\
      <xsd:element name="Elemento">
        <xsd:simpleType>
          <xsd:restriction base="xsd:int">
            <xsd:enumeration value="1"/>
            <xsd:enumeration value="3"/>
            <xsd:enumeration value="5"/>
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>""", output="Elemento"))

    client_named = testutils.client_from_wsdl(testutils.wsdl("""\
      <xsd:simpleType name="MyType">
        <xsd:restriction base="xsd:int">
          <xsd:enumeration value="1"/>
          <xsd:enumeration value="3"/>
          <xsd:enumeration value="5"/>
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:element name="Elemento" type="ns:MyType"/>""", output="Elemento"))

    client_twice_restricted = testutils.client_from_wsdl(testutils.wsdl("""\
      <xsd:simpleType name="MyTypeGeneric">
        <xsd:restriction base="xsd:int">
          <xsd:enumeration value="1"/>
          <xsd:enumeration value="2"/>
          <xsd:enumeration value="3"/>
          <xsd:enumeration value="4"/>
          <xsd:enumeration value="5"/>
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:simpleType name="MyType">
        <xsd:restriction base="ns:MyTypeGeneric">
          <xsd:enumeration value="1"/>
          <xsd:enumeration value="3"/>
          <xsd:enumeration value="5"/>
        </xsd:restriction>
      </xsd:simpleType>
      <xsd:element name="Elemento" type="ns:MyType"/>""", output="Elemento"))

    for client in (client_unnamed, client_named, client_twice_restricted):
        response = client.service.f(__inject=dict(reply=suds.byte_str("""\
<?xml version="1.0"?>
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Body>
    <Elemento xmlns="my-namespace">5</Elemento>
  </Body>
</Envelope>""")))
        assert response.__class__ is int
        assert response == 5
Exemplo n.º 54
0
def test_WSDL_import():
    wsdl = tests.wsdl("", wsdl_target_namespace="bingo-bongo")
    wsdl_wrapper = suds.byte_str("""\
<?xml version='1.0' encoding='UTF-8'?>
<wsdl:definitions
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="bingo-bongo">
  <wsdl:import namespace="bingo-bongo" location="suds://wsdl"/>
</wsdl:definitions>
""")
    store = suds.store.DocumentStore(wsdl=wsdl, wsdl_wrapper=wsdl_wrapper)
    client = suds.client.Client("suds://wsdl_wrapper", documentStore=store,
        cache=None, nosend=True)
    client.service.f()
Exemplo n.º 55
0
    def send(self, request):
        if 'SOAPAction' in request.headers:
            if self.responses is None:
                pytest.fail("No responses set with mock_transport.set_responses()")
            try:
                response = next(self.responses)
            except StopIteration:
                pytest.fail(
                    "Not enought responses available set with mock_transport.set_responses()")

            return suds.transport.Reply(
                http_client.OK, {}, suds.byte_str(response))

        pytest.fail("No SOAPAction header in request {}".format(request.headers))
Exemplo n.º 56
0
    def create_test_document():
        input_data = suds.byte_str("""\
<xsd:element name="ZuZu">
   <xsd:simpleType>
      <xsd:restriction base="xsd:string">
         <xsd:enumeration value="alfa"/>
         <xsd:enumeration value="beta"/>
         <xsd:enumeration value="gamma"/>
      </xsd:restriction>
   </xsd:simpleType>
</xsd:element>""")
        document = suds.sax.parser.Parser().parse(suds.BytesIO(input_data))
        assert document.__class__ is Document
        return document
Exemplo n.º 57
0
    def test_operation_request_and_reply(self):
        xsd_content = '<xsd:element name="Data" type="xsd:string"/>'
        web_service_URL = "Great minds think alike"
        xsd_target_namespace = "omicron psi"
        wsdl = testutils.wsdl(
            suds.byte_str(xsd_content),
            operation_name="pi",
            xsd_target_namespace=xsd_target_namespace,
            input="Data",
            output="Data",
            web_service_URL=web_service_URL,
        )
        test_input_data = "Riff-raff"
        test_output_data = "La-di-da-da-da"
        store = MockDocumentStore(wsdl=wsdl)
        transport = MockTransport(
            send_data=suds.byte_str(
                """\
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Body>
    <Data xmlns="%s">%s</Data>
  </env:Body>
</env:Envelope>"""
                % (xsd_target_namespace, test_output_data)
            )
        )
        client = suds.client.Client("suds://wsdl", documentStore=store, cache=None, transport=transport)
        assert transport.mock_log == []
        reply = client.service.pi(test_input_data)
        assert len(transport.mock_log) == 1
        assert transport.mock_log[0][0] == "send"
        assert transport.mock_log[0][1][0] == web_service_URL
        request_message = transport.mock_log[0][1][1]
        assert suds.byte_str(xsd_target_namespace) in request_message
        assert suds.byte_str(test_input_data) in request_message
        assert reply == test_output_data