File: test_client.py

package info (click to toggle)
python-zeep 4.3.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,600 kB
  • sloc: python: 15,551; makefile: 13
file content (321 lines) | stat: -rw-r--r-- 10,197 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import os

import pytest
import requests_mock

from tests.utils import load_xml
from zeep import client, xsd
from zeep.exceptions import Error
from zeep.transports import Transport
from zeep.wsdl import Document


def test_bind():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    service = client_obj.bind()
    assert service


def test_bind_existing_document():
    wsdl = Document("tests/wsdl_files/soap.wsdl", transport=Transport())
    client_obj = client.Client(wsdl)
    service = client_obj.bind()
    assert service


def test_unknown_transport():
    client_obj = client.Client("tests/wsdl_files/soap_transport_err.wsdl")
    service = client_obj.bind()
    assert service


def test_bind_service():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    service = client_obj.bind("StockQuoteService")
    assert service


def test_bind_service_port():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    service = client_obj.bind("StockQuoteService", "StockQuotePort")
    assert service


def test_service_proxy_ok():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    assert client_obj.service.GetLastTradePrice


def test_service_proxy_non_existing():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    with pytest.raises(AttributeError):
        assert client_obj.service.NonExisting


def test_context_manager():
    with client.Client("tests/wsdl_files/soap.wsdl") as c:
        assert c


def test_service_proxy_dir_operations():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    operations = [op for op in dir(client_obj.service) if not op.startswith("_")]
    assert set(operations) == {"GetLastTradePrice", "GetLastTradePriceNoOutput"}


def test_operation_proxy_doc():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    assert (
        client_obj.service.GetLastTradePrice.__doc__
        == "GetLastTradePrice(tickerSymbol: xsd:string, "
        "account: ns0:account, "
        "country: ns0:country) -> price: xsd:float"
    )


def test_open_from_file_object():
    with open("tests/wsdl_files/soap_transport_err.wsdl", "rb") as fh:
        client_obj = client.Client(fh)
        service = client_obj.bind()
        assert service


def test_client_no_wsdl():
    with pytest.raises(ValueError):
        client.Client(None)


def test_client_cache_service():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    assert client_obj.service.GetLastTradePrice
    assert client_obj.service.GetLastTradePrice


def test_force_https():
    with open("tests/wsdl_files/soap.wsdl") as fh:
        response = fh.read()

    with requests_mock.mock() as m:
        url = "https://tests.python-zeep.org/wsdl"
        m.get(url, text=response, status_code=200)
        client_obj = client.Client(url)
        binding_options = client_obj.service._binding_options
        assert binding_options["address"].startswith("https")

        expected_url = "https://example.com/stockquote"
        assert binding_options["address"] == expected_url

    with open("tests/wsdl_files/http.wsdl") as fh:
        response = fh.read()

    with requests_mock.mock() as m:
        url = "https://tests.python-zeep.org/wsdl"
        m.get(url, text=response, status_code=200)
        client_obj = client.Client(url)
        binding_options = client_obj.service._binding_options
        assert binding_options["address"].startswith("https")

        expected_url = "https://example.com/stockquote"
        assert binding_options["address"] == expected_url


@pytest.mark.requests
def test_create_service():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    service = client_obj.create_service(
        "{http://example.com/stockquote.wsdl}StockQuoteBinding",
        "http://test.python-zeep.org/x",
    )

    response = """
    <?xml version="1.0"?>
    <soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:stoc="http://example.com/stockquote.xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <stoc:TradePrice>
             <price>120.123</price>
          </stoc:TradePrice>
       </soapenv:Body>
    </soapenv:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://test.python-zeep.org/x", text=response)
        result = service.GetLastTradePrice("foobar")
        assert result == 120.123
        assert m.request_history[0].headers["User-Agent"].startswith("Zeep/")
        assert m.request_history[0].body.startswith(
            b"<?xml version='1.0' encoding='utf-8'?>"
        )


def test_create_message():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    data = client_obj.create_message(
        client_obj.service, "GetLastTradePrice", tickerSymbol="ZEEP"
    )
    assert data is not None


@pytest.mark.skipif(os.name == "nt", reason="test valid for unix platforms only")
def test_load_wsdl_with_file_prefix_unix():
    cwd = os.path.dirname(__file__)
    client.Client("file://" + os.path.join(cwd, "wsdl_files/soap.wsdl"))


@pytest.mark.skipif(os.name != "nt", reason="test valid for windows platform only")
def test_load_wsdl_with_file_prefix():
    cwd = os.path.dirname(__file__)
    # RFC 8089 REQUIRES that separators in file uris use forward slashes
    uri = ("file:///" + os.path.join(cwd, "wsdl_files/soap.wsdl")).replace("\\", "/")
    client.Client(uri)


@pytest.mark.requests
def test_service_proxy():
    client_obj = client.Client("tests/wsdl_files/soap.wsdl")

    response = """
    <?xml version="1.0"?>
    <soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:stoc="http://example.com/stockquote.xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <stoc:TradePrice>
             <price>120.123</price>
          </stoc:TradePrice>
       </soapenv:Body>
    </soapenv:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://example.com/stockquote", text=response)
        result = client_obj.service.GetLastTradePrice("foobar")
        assert result == 120.123


@pytest.mark.requests
def test_call_method_fault():
    obj = client.Client("tests/wsdl_files/soap.wsdl")

    response = """
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope
            xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap:Body>
            <soap:Fault>
              <faultcode>soap:Server</faultcode>
              <faultstring>
                Big fatal error!!
              </faultstring>
              <faultactor>StockListByDate</faultactor>
              <detail>
                <Error xmlns="http://sherpa.sherpaan.nl/Sherpa">
                  <ErrorMessage>wrong security code</ErrorMessage>
                  <ErrorSource>StockListByDate</ErrorSource>
                </Error>
              </detail>
            </soap:Fault>
          </soap:Body>
        </soap:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://example.com/stockquote", text=response, status_code=500)
        with pytest.raises(Error):
            obj.service.GetLastTradePrice(tickerSymbol="foobar")


@pytest.mark.requests
def test_default_soap_headers():
    header = xsd.ComplexType(
        xsd.Sequence(
            [
                xsd.Element("{http://tests.python-zeep.org}name", xsd.String()),
                xsd.Element("{http://tests.python-zeep.org}password", xsd.String()),
            ]
        )
    )
    header_value = header(name="ik", password="foo")

    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    client_obj.set_default_soapheaders([header_value])

    response = """
    <?xml version="1.0"?>
    <soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:stoc="http://example.com/stockquote.xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <stoc:TradePrice>
             <price>120.123</price>
          </stoc:TradePrice>
       </soapenv:Body>
    </soapenv:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://example.com/stockquote", text=response)
        client_obj.service.GetLastTradePrice("foobar")

        doc = load_xml(m.request_history[0].body)
        header = doc.find("{http://schemas.xmlsoap.org/soap/envelope/}Header")
        assert header is not None
        assert len(list(header)) == 2


@pytest.mark.requests
def test_default_soap_headers_extra():
    header = xsd.ComplexType(
        xsd.Sequence(
            [
                xsd.Element("{http://tests.python-zeep.org}name", xsd.String()),
                xsd.Element("{http://tests.python-zeep.org}password", xsd.String()),
            ]
        )
    )
    header_value = header(name="ik", password="geheim")

    extra_header = xsd.ComplexType(
        xsd.Sequence(
            [
                xsd.Element("{http://tests.python-zeep.org}name", xsd.String()),
                xsd.Element("{http://tests.python-zeep.org}password", xsd.String()),
            ]
        )
    )
    extra_header_value = extra_header(name="ik", password="geheim")

    client_obj = client.Client("tests/wsdl_files/soap.wsdl")
    client_obj.set_default_soapheaders([header_value])

    response = """
    <?xml version="1.0"?>
    <soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:stoc="http://example.com/stockquote.xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <stoc:TradePrice>
             <price>120.123</price>
          </stoc:TradePrice>
       </soapenv:Body>
    </soapenv:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://example.com/stockquote", text=response)
        client_obj.service.GetLastTradePrice(
            "foobar", _soapheaders=[extra_header_value]
        )

        doc = load_xml(m.request_history[0].body)
        header = doc.find("{http://schemas.xmlsoap.org/soap/envelope/}Header")
        assert header is not None
        assert len(list(header)) == 4