# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify it under
# the terms of the (LGPL) GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Library Lesser General Public License
# for more details at ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# written by: Jurko Gospodnetić ( jurko.gospodnetic@pke.hr )
"""
Suds Python library request construction related unit tests.
Suds provides the user with an option to automatically 'hide' wrapper elements
around simple types and allow the user to specify such parameters without
explicitly creating those wrappers. For example: function taking a parameter of
type X, where X is a sequence containing only a single simple data type (e.g.
string or integer) will be callable by directly passing it that internal simple
data type value instead of first wrapping that value in an object of type X and
then passing that wrapper object instead.
"""
import testutils
from testutils import _assert_request_content
if __name__ == "__main__":
testutils.run_using_pytest(globals())
import suds
import suds.store
import pytest
#TODO: Update the current restriction type output parameter handling so such
# parameters get converted to the correct Python data type based on the
# restriction's underlying data type.
@pytest.mark.xfail
def test_bare_input_restriction_types():
client_unnamed = testutils.client_from_wsdl(testutils.wsdl("""\
""", input="Elemento", operation_name="f"))
client_named = testutils.client_from_wsdl(testutils.wsdl("""\
""", input="Elemento",
operation_name="f"))
assert not _is_input_wrapped(client_unnamed, "f")
assert not _is_input_wrapped(client_named, "f")
def parametrize_single_element_input_test(param_names, param_values):
"""
Define different parametrized single element input test function calls.
Parameter value input is a tuple containing 2+ parameters:
* 1. element - input XSD element definition
* 2. element - input element name
* 3+ elements - tuples containing the following:
* position argument list for the invoked test web service operation
* expected request body content for the given arguments
* [optional] reason for marking this test case as expected to fail
"""
mark = pytest
expanded_param_values = []
for param_value in param_values:
xsd, external_element_name = param_value[0:2]
for next_value in param_value[2:]:
assert len(next_value) in (2, 3)
args, request_body = next_value[:2]
xfail = len(next_value) == 3
param = (xsd, external_element_name, args, request_body)
# Manually skip xfails for now since there's no way to mark
if not xfail:
expanded_param_values.append(param)
return (param_names, expanded_param_values), {}
@pytest.mark.indirect_parametrize(parametrize_single_element_input_test,
("xsd", "external_element_name", "args", "request_body"), (
# Bare non-optional element.
('', "a",
([], ""),
([5], "5")),
# Bare optional element.
('', "a",
([], ""),
([5], "5")),
# Choice with a non-empty sub-sequence.
("""\
""", "Wrapper",
([], "",
"non-optional choice handling buggy"),
([5], "5"),
([None, 1], "1",
"non-optional choice handling buggy"),
([None, 1, 2],
"12"),
([None, None, 1],
"1",
"non-optional choice handling buggy")),
# Choice with a non-optional element.
("""\
""", "Wrapper",
([], "",
"non-optional choice handling buggy"),
([5], "5")),
# Choice with an optional element.
("""\
""", "Wrapper",
([], ""),
([5], "5")),
# Choices with multiple elements, at least one of which is optional.
("""\
""", "Wrapper",
([], ""),
([5], "5"),
([None, 5], "5")),
("""\
""", "Wrapper",
([], ""),
([5], "5"),
([None, 5], "5")),
("""\
""", "Wrapper",
([], ""),
([5], "5"),
([None, 5], "5")),
# Choice with multiple non-empty sub-sequences.
("""\
""", "Wrapper",
([], "",
"non-optional choice handling buggy"),
([5], "5",
"non-optional choice handling buggy"),
([5, 9], """\
5
9
"""),
([None, 1], "1",
"non-optional choice handling buggy"),
([None, None, 1],
"1",
"non-optional choice handling buggy"),
([None, None, 1, 2],
"12"),
([None, None, None, 1],
"1",
"non-optional choice handling buggy")),
# Empty choice.
("""\
""", "Wrapper",
([], "")),
# Empty sequence.
("""\
""", "Wrapper",
([], "")),
# Optional choice.
("""\
""", "Wrapper",
([], "",
# This test passes by accident - the following two bugs seem to
# cancel each other out:
# - choice order indicators explicitly marked optional unsupported
# - not constructing correct input parameter values when using no
# input arguments for a choice
#"suds does not yet support minOccurs/maxOccurs attributes on all/"
#"choice/sequence order indicators"),
),
([5], "5"),
([None, 1],
"1")),
# Optional sequence.
("""\
""", "Wrapper",
([], "",
"suds does not yet support minOccurs/maxOccurs attributes on all/"
"choice/sequence order indicators"),
([5], "5"),
([None, 1],
"1"),
([1, 2], """\
1
2
""")),
# Sequence with a non-empty sub-sequence.
("""\
""", "Wrapper",
([], ""),
([5], "5"),
([None, 1],
"1"),
([None, 1, 2], """\
1
2
"""),
([None, None, 1],
"1")),
# Sequence with a non-optional element.
("""\
""", "Wrapper",
([], ""),
([5], "5")),
# Sequence with an optional element.
("""\
""", "Wrapper",
([], ""),
([5], "5")),
# Sequence with multiple consecutive choices.
("""\
""", "Wrapper",
([], "",
"non-optional choice handling buggy"),
([5], "5"),
([None, 1, 2], """\
1
2
"""),
([None, 1, None, 2], """\
1
2
""")),
# Sequence with multiple optional elements.
("""\
""", "Wrapper",
([], ""),
([5], "5"),
([None, 1], "1"),
([5, 1],
"51")),
))
def test_document_literal_request_for_single_element_input(xsd,
external_element_name, args, request_body):
wsdl = testutils.wsdl(xsd, input=external_element_name,
xsd_target_namespace="dr. Doolittle", operation_name="f")
client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
_assert_request_content(client.service.f(*args), """\
%s
""" % (request_body,))
def test_disabling_automated_simple_interface_unwrapping():
xsd_target_namespace = "woof"
wsdl = testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace)
client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True,
unwrap=False)
assert not _is_input_wrapped(client, "f")
element_data = "Wonderwall"
wrapper = client.factory.create("my_xsd:Wrapper")
wrapper.Elemento = element_data
_assert_request_content(client.service.f(Wrapper=wrapper), """\
%s
""" % (xsd_target_namespace, element_data))
def test_element_references_to_different_namespaces():
wsdl = suds.byte_str("""\
""")
external_schema = suds.byte_str("""\
""")
store = suds.store.DocumentStore(external_schema=external_schema,
wsdl=wsdl)
client = suds.client.Client("suds://wsdl", cache=None, documentStore=store,
nosend=True, prettyxml=True)
_assert_request_content(client.service.f(local="--L--",
local_referenced="--LR--", external="--E--"), """\
--L--
--LR--
--E--
""")
def test_function_with_reserved_characters():
wsdl = suds.byte_str("""\
""")
store = suds.store.DocumentStore(wsdl=wsdl)
client = suds.client.Client("suds://wsdl", cache=None, documentStore=store,
nosend=True, prettyxml=True)
operation_name = ".f"
method = getattr(client.service, operation_name)
request = method(local="--L--")
_assert_request_content(request, """\
--L--
""")
def test_invalid_input_parameter_type_handling():
"""
Input parameters of invalid type get silently pushed into the constructed
SOAP request as strings, even though the constructed SOAP request does not
necessarily satisfy requirements set for it in the web service's WSDL
schema. It is then left up to the web service implementation to detect and
report this error.
"""
xsd_target_namespace = "1234567890"
wsdl = testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace)
client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
# Passing an unrelated Python type value.
class SomeType:
def __str__(self):
return "Some string representation."
_assert_request_content(client.service.f(anInteger=SomeType()), """\
Some string representation.
""" % (xsd_target_namespace,))
# Passing a value of a WSDL schema defined type.
value = client.factory.create("my_xsd:Freakazoid")
value.freak1 = "Tiny"
value.freak2 = "Miny"
value.freak3 = "Mo"
_assert_request_content(client.service.f(anInteger=value), """\
Tiny
Miny
Mo
""" % (xsd_target_namespace,))
def test_missing_parameters():
"""Missing non-optional parameters should get passed as empty values."""
xsd_target_namespace = "plonker"
service = _service_from_wsdl(testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace))
_assert_request_content(service.f(), """\
""" % (xsd_target_namespace,))
_assert_request_content(service.f(("Pero \u017Ddero")), """\
Pero \u017Ddero
""" % (xsd_target_namespace,))
_assert_request_content(service.f(anInteger=666), """\
666
""" % (xsd_target_namespace,))
# None value is treated the same as undefined.
_assert_request_content(service.f(aString=None, anInteger=666), """\
666
""" % (xsd_target_namespace,))
_assert_request_content(service.f(aString="Omega", anInteger=None), """\
Omega
""" % (xsd_target_namespace,))
def test_named_parameter():
class Tester:
def __init__(self, service, expected_xml):
self.service = service
self.expected_xml = expected_xml
def test(self, *args, **kwargs):
request = self.service.f(*args, **kwargs)
_assert_request_content(request, self.expected_xml)
# Test different ways to make the same web service operation call.
xsd_target_namespace = "qwerty"
service = _service_from_wsdl(testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace))
t = Tester(service, """\
einz
zwei
""" % (xsd_target_namespace,))
t.test("einz", "zwei")
t.test(uno="einz", due="zwei")
t.test(due="zwei", uno="einz")
t.test("einz", due="zwei")
# The order of parameters in the constructed SOAP request should depend
# only on the initial WSDL schema.
xsd_target_namespace = "abracadabra"
service = _service_from_wsdl(testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace))
t = Tester(service, """\
zwei
einz
""" % (xsd_target_namespace,))
t.test("zwei", "einz")
t.test(uno="einz", due="zwei")
t.test(due="zwei", uno="einz")
t.test("zwei", uno="einz")
def test_optional_parameter_handling():
"""Missing optional parameters should not get passed at all."""
xsd_target_namespace = "RoOfIe"
service = _service_from_wsdl(testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace))
_assert_request_content(service.f(), """\
""" % (xsd_target_namespace,))
# None is treated as an undefined value.
_assert_request_content(service.f(None), """\
""" % (xsd_target_namespace,))
# Empty string values are treated as well defined values.
_assert_request_content(service.f(""), """\
""" % (xsd_target_namespace,))
_assert_request_content(service.f("Kiflica"), """\
Kiflica
""" % (xsd_target_namespace,))
_assert_request_content(service.f(anInteger=666), """\
666
""" % (xsd_target_namespace,))
_assert_request_content(service.f("Alfa", 9), """\
Alfa
9
""" % (xsd_target_namespace,))
def test_optional_parameter_with_empty_object_value():
"""Missing optional parameters should not get passed at all."""
xsd_target_namespace = "I'm a cute little swamp gorilla monster!"
wsdl = testutils.wsdl("""\
""", input="Wrapper", operation_name="f",
xsd_target_namespace=xsd_target_namespace)
client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
service = client.service
# Base line: nothing passed --> nothing marshalled.
_assert_request_content(service.f(), """\
""" % (xsd_target_namespace,))
# Passing a empty object as an empty dictionary.
_assert_request_content(service.f({}), """\
""" % (xsd_target_namespace,))
# Passing a empty explicitly constructed `suds.sudsobject.Object`.
empty_object = client.factory.create("my_xsd:Wrapper")
_assert_request_content(service.f(empty_object), """\
""" % (xsd_target_namespace,))
def test_SOAP_headers():
"""Rudimentary 'soapheaders' option usage test."""
wsdl = suds.byte_str("""\
""")
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(), """\
""" % (header_data,))
def test_twice_wrapped_parameter():
"""
Suds does not recognize 'twice wrapped' data structures and unwraps the
external one but keeps the internal wrapping structure in place.
"""
xsd_target_namespace = "spank me"
wsdl = testutils.wsdl("""\
""", input="Wrapper1", operation_name="f",
xsd_target_namespace=xsd_target_namespace)
client = testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
assert _is_input_wrapped(client, "f")
# Web service operation calls made with 'valid' parameters.
#
# These calls are actually illegal and result in incorrectly generated SOAP
# requests not matching the relevant WSDL schema. To make them valid we
# would need to pass a more complex value instead of a simple string, but
# the current simpler solution is good enough for what we want to test
# here.
value = "A B C"
expected_request = """\
%s
""" % (xsd_target_namespace, value)
_assert_request_content(client.service.f(value), expected_request)
_assert_request_content(client.service.f(Wrapper2=value), expected_request)
# Web service operation calls made with 'invalid' parameters.
def test_invalid_parameter(**kwargs):
assert len(kwargs) == 1
keyword = next(iter(kwargs.keys()))
expected = "f() got an unexpected keyword argument '%s'" % (keyword,)
e = pytest.raises(TypeError, client.service.f, **kwargs).value
try:
assert str(e) == expected
finally:
del e # explicitly break circular reference chain in Python 3
test_invalid_parameter(Elemento=value)
test_invalid_parameter(Wrapper1=value)
def test_wrapped_parameter(monkeypatch):
monkeypatch.delitem(locals(), "e", False)
# Prepare web service proxies.
def client(xsd, *input):
wsdl = testutils.wsdl(xsd, input=input, xsd_target_namespace="toolyan",
operation_name="f")
return testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True)
client_bare_single = client("""\
""", "Elemento")
client_bare_multiple_simple = client("""\
""", "Elemento1",
"Elemento2")
client_bare_multiple_wrapped = client("""\
""", "Elemento1",
"Elemento2")
client_wrapped_unnamed = client("""\
""", "Wrapper")
client_wrapped_named = client("""\
""", "Wrapper")
# Make sure suds library interprets our WSDL definitions as wrapped or bare
# input interfaces as expected.
assert not _is_input_wrapped(client_bare_single, "f")
assert not _is_input_wrapped(client_bare_multiple_simple, "f")
assert not _is_input_wrapped(client_bare_multiple_wrapped, "f")
assert _is_input_wrapped(client_wrapped_unnamed, "f")
assert _is_input_wrapped(client_wrapped_named, "f")
# Both bare & wrapped single parameter input web service operations get
# called the same way even though the wrapped one actually has an extra
# wrapper element around its input data.
data = "Maestro"
def call_single(c):
return c.service.f(data)
_assert_request_content(call_single(client_bare_single), """\
%s
""" % (data,))
expected_xml = """\
%s
""" % (data,)
_assert_request_content(call_single(client_wrapped_unnamed), expected_xml)
_assert_request_content(call_single(client_wrapped_named), expected_xml)
# Suds library's automatic structure unwrapping prevents us from specifying
# the external wrapper structure directly.
e = pytest.raises(TypeError, client_wrapped_unnamed.service.f, Wrapper="A")
try:
expected = "f() got an unexpected keyword argument 'Wrapper'"
assert str(e.value) == expected
finally:
del e # explicitly break circular reference chain in Python 3
# Multiple parameter web service operations are never automatically
# unwrapped.
data = ("Unga", "Bunga")
def call_multiple(c):
return c.service.f(*data)
_assert_request_content(call_multiple(client_bare_multiple_simple), """\
%s
%s
""" % data)
_assert_request_content(call_multiple(client_bare_multiple_wrapped), """\
%s
%s
""" % data)
###############################################################################
#
# Test utilities.
#
###############################################################################
def _is_input_wrapped(client, method_name):
assert len(client.wsdl.bindings) == 1
binding = next(iter(client.wsdl.bindings.values()))
operation = binding.operations[method_name]
return operation.soap.input.body.wrapped
def _service_from_wsdl(wsdl):
"""
Construct a suds Client service instance used in tests in this module.
The constructed Client instance only prepares web service operation
invocation requests and does not attempt to actually send them.
"""
return testutils.client_from_wsdl(wsdl, nosend=True, prettyxml=True).service