File: test_pipeline.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (430 lines) | stat: -rw-r--r-- 15,220 bytes parent folder | download
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------

from unittest.mock import Mock
import json
from io import BytesIO
import xml.etree.ElementTree as ET

import pytest
import httpx
import requests

from corehttp.rest import HttpRequest
from corehttp.runtime.pipeline import Pipeline
from corehttp.runtime import PipelineClient
from corehttp.runtime.policies import (
    SansIOHTTPPolicy,
    UserAgentPolicy,
    RetryPolicy,
    HTTPPolicy,
)
from corehttp.runtime._base import PipelineClientBase, _format_url_section
from corehttp.transport import HttpTransport
from corehttp.transport.requests import RequestsTransport
from corehttp.transport.httpx import HttpXTransport
from corehttp.exceptions import BaseError

from utils import SYNC_TRANSPORTS


def test_sans_io_exception():
    class BrokenSender(HttpTransport):
        def send(self, request, **config):
            raise ValueError("Broken")

        def open(self):
            self.session = requests.Session()

        def close(self):
            self.session.close()

        def __exit__(self, exc_type, exc_value, traceback):
            """Raise any exception triggered within the runtime context."""
            return self.close()

    pipeline = Pipeline(BrokenSender(), [SansIOHTTPPolicy()])

    req = HttpRequest("GET", "/")
    with pytest.raises(ValueError):
        pipeline.run(req)


def test_invalid_policy_error():
    # non-HTTPPolicy/non-SansIOHTTPPolicy should raise an error
    class FooPolicy:
        pass

    # only on_request should raise an error
    class OnlyOnRequestPolicy:
        def on_request(self, request):
            pass

    # only on_response should raise an error
    class OnlyOnResponsePolicy:
        def on_response(self, request, response):
            pass

    with pytest.raises(AttributeError):
        pipeline = Pipeline(transport=Mock(), policies=[FooPolicy()])

    with pytest.raises(AttributeError):
        pipeline = Pipeline(transport=Mock(), policies=[OnlyOnRequestPolicy()])

    with pytest.raises(AttributeError):
        pipeline = Pipeline(transport=Mock(), policies=[OnlyOnResponsePolicy()])


@pytest.mark.parametrize("transport", SYNC_TRANSPORTS)
def test_transport_socket_timeout(transport):
    request = HttpRequest("GET", "https://bing.com")
    policies = [UserAgentPolicy("myusergant")]
    # Sometimes this will raise a read timeout, sometimes a socket timeout depending on timing.
    # Either way, the error should always be wrapped as an BaseError to ensure it's caught
    # by the retry policy.
    with pytest.raises(BaseError):
        with Pipeline(transport(), policies=policies) as pipeline:
            response = pipeline.run(request, connection_timeout=0.000001, read_timeout=0.000001)


def test_format_url_basic():
    client = PipelineClientBase("https://bing.com")
    formatted = client.format_url("/{foo}", foo="bar")
    assert formatted == "https://bing.com/bar"


def test_format_url_with_query():
    client = PipelineClientBase("https://bing.com/path?query=testvalue&x=2ndvalue")
    formatted = client.format_url("/{foo}", foo="bar")
    assert formatted == "https://bing.com/path/bar?query=testvalue&x=2ndvalue"


def test_format_url_missing_param_values():
    client = PipelineClientBase("https://bing.com/path")
    formatted = client.format_url("/{foo}")
    assert formatted == "https://bing.com/path"


def test_format_url_missing_param_values_with_query():
    client = PipelineClientBase("https://bing.com/path?query=testvalue&x=2ndvalue")
    formatted = client.format_url("/{foo}")
    assert formatted == "https://bing.com/path?query=testvalue&x=2ndvalue"


def test_format_url_extra_path():
    client = PipelineClientBase("https://bing.com/path")
    formatted = client.format_url("/subpath/{foo}", foo="bar")
    assert formatted == "https://bing.com/path/subpath/bar"


def test_format_url_complex_params():
    client = PipelineClientBase("https://bing.com/path")
    formatted = client.format_url("/subpath/{a}/{b}/foo/{c}/bar", a="X", c="Y")
    assert formatted == "https://bing.com/path/subpath/X/foo/Y/bar"


def test_format_url_extra_path_missing_values():
    client = PipelineClientBase("https://bing.com/path")
    formatted = client.format_url("/subpath/{foo}")
    assert formatted == "https://bing.com/path/subpath"


def test_format_url_extra_path_missing_values_with_query():
    client = PipelineClientBase("https://bing.com/path?query=testvalue&x=2ndvalue")
    formatted = client.format_url("/subpath/{foo}")
    assert formatted == "https://bing.com/path/subpath?query=testvalue&x=2ndvalue"


def test_format_url_full_url():
    client = PipelineClientBase("https://bing.com/path")
    formatted = client.format_url("https://google.com/subpath/{foo}", foo="bar")
    assert formatted == "https://google.com/subpath/bar"


def test_format_url_no_endpoint():
    client = PipelineClientBase(None)
    formatted = client.format_url("https://google.com/subpath/{foo}", foo="bar")
    assert formatted == "https://google.com/subpath/bar"


def test_format_url_double_query():
    client = PipelineClientBase("https://bing.com/path?query=testvalue&x=2ndvalue")
    formatted = client.format_url("/subpath?a=X&c=Y")
    assert formatted == "https://bing.com/path/subpath?query=testvalue&x=2ndvalue&a=X&c=Y"


def test_format_url_braces_with_dot():
    endpoint = "https://bing.com/{aaa.bbb}"
    with pytest.raises(ValueError):
        url = _format_url_section(endpoint)


def test_format_url_single_brace():
    endpoint = "https://bing.com/{aaa.bbb"
    with pytest.raises(ValueError):
        url = _format_url_section(endpoint)


def test_format_incorrect_endpoint():
    client = PipelineClientBase("{Endpoint}/text/analytics/v3.0")
    with pytest.raises(ValueError) as exp:
        client.format_url("foo/bar")
    assert (
        str(exp.value) == "The value provided for the url part Endpoint was incorrect, and resulted in an invalid url"
    )


def test_request_json():

    data = "Lots of dataaaa"
    request = HttpRequest("GET", "/", json=data)

    assert request.content == json.dumps(data)
    assert request.headers.get("Content-Length") == "17"


def test_request_data():

    data = "Lots of dataaaa"
    request = HttpRequest("GET", "/", content=data)

    assert request.content == data
    assert request.headers.get("Content-Length") == "15"


def test_request_stream():
    data = b"Lots of dataaaa"
    request = HttpRequest("GET", "/", content=data)
    assert request.content == data

    def data_gen():
        for i in range(10):
            yield i

    data = data_gen()
    request = HttpRequest("GET", "/", content=data)
    assert request.content == data

    data = BytesIO(b"Lots of dataaaa")
    request = HttpRequest("GET", "/", content=data)
    assert request.content == data


def test_request_xml():
    data = ET.Element("root")
    request = HttpRequest("GET", "/", content=data)
    assert request.content == b"<?xml version='1.0' encoding='utf-8'?>\n<root />"


def test_request_url_with_params():
    request = HttpRequest("GET", "a/b/c?t=y", params={"g": "h"})
    assert request.url in ["a/b/c?g=h&t=y", "a/b/c?t=y&g=h"]


def test_request_url_with_params_as_list():
    request = HttpRequest("GET", "a/b/c?t=y", params={"g": ["h", "i"]})
    assert request.url in ["a/b/c?g=h&g=i&t=y", "a/b/c?t=y&g=h&g=i"]


def test_request_url_with_params_with_none_in_list():
    with pytest.raises(ValueError):
        HttpRequest("GET", "a/b/c?t=y", params={"g": ["h", None]})


def test_request_url_with_params_with_none():
    with pytest.raises(ValueError):
        HttpRequest("GET", "a/b/c?t=y", params={"g": None})


def test_repr():
    request = HttpRequest("GET", "hello.com")
    assert repr(request) == "<HttpRequest [GET], url: 'hello.com'>"


def test_add_custom_policy():
    class BooPolicy(HTTPPolicy):
        def send(*args):
            raise BaseError("boo")

    class FooPolicy(HTTPPolicy):
        def send(*args):
            raise BaseError("boo")

    retry_policy = RetryPolicy()
    boo_policy = BooPolicy()
    foo_policy = FooPolicy()
    client = PipelineClient(endpoint="test", policies=[retry_policy], per_call_policies=boo_policy)
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo < pos_retry

    client = PipelineClient(endpoint="test", policies=[retry_policy], per_call_policies=[boo_policy])
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo < pos_retry

    client = PipelineClient(endpoint="test", policies=[retry_policy], per_retry_policies=boo_policy)
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo > pos_retry

    client = PipelineClient(endpoint="test", policies=[retry_policy], per_retry_policies=[boo_policy])
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo > pos_retry

    client = PipelineClient(
        endpoint="test", policies=[retry_policy], per_call_policies=boo_policy, per_retry_policies=foo_policy
    )
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    assert foo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_foo = policies.index(foo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo < pos_retry
    assert pos_foo > pos_retry

    client = PipelineClient(
        endpoint="test", policies=[retry_policy], per_call_policies=[boo_policy], per_retry_policies=[foo_policy]
    )
    policies = client.pipeline._impl_policies
    assert boo_policy in policies
    assert foo_policy in policies
    pos_boo = policies.index(boo_policy)
    pos_foo = policies.index(foo_policy)
    pos_retry = policies.index(retry_policy)
    assert pos_boo < pos_retry
    assert pos_foo > pos_retry

    policies = [UserAgentPolicy(), RetryPolicy()]
    client = PipelineClient(endpoint="test", policies=policies, per_call_policies=boo_policy)
    actual_policies = client.pipeline._impl_policies
    assert boo_policy == actual_policies[0]
    client = PipelineClient(endpoint="test", policies=policies, per_call_policies=[boo_policy])
    actual_policies = client.pipeline._impl_policies
    assert boo_policy == actual_policies[0]

    client = PipelineClient(endpoint="test", policies=policies, per_retry_policies=foo_policy)
    actual_policies = client.pipeline._impl_policies
    assert foo_policy == actual_policies[2]
    client = PipelineClient(endpoint="test", policies=policies, per_retry_policies=[foo_policy])
    actual_policies = client.pipeline._impl_policies
    assert foo_policy == actual_policies[2]

    client = PipelineClient(
        endpoint="test", policies=policies, per_call_policies=boo_policy, per_retry_policies=foo_policy
    )
    actual_policies = client.pipeline._impl_policies
    assert boo_policy == actual_policies[0]
    assert foo_policy == actual_policies[3]
    client = PipelineClient(
        endpoint="test", policies=policies, per_call_policies=[boo_policy], per_retry_policies=[foo_policy]
    )
    actual_policies = client.pipeline._impl_policies
    assert boo_policy == actual_policies[0]
    assert foo_policy == actual_policies[3]

    policies = [UserAgentPolicy()]
    with pytest.raises(ValueError):
        client = PipelineClient(endpoint="test", policies=policies, per_retry_policies=foo_policy)
    with pytest.raises(ValueError):
        client = PipelineClient(endpoint="test", policies=policies, per_retry_policies=[foo_policy])


def test_basic_requests(port):
    request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    with Pipeline(RequestsTransport(), policies=policies) as pipeline:
        response = pipeline.run(request)

    assert pipeline._transport.session is None
    assert isinstance(response.http_response.status_code, int)


def test_basic_options_requests(port):

    request = HttpRequest("OPTIONS", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    with Pipeline(RequestsTransport(), policies=policies) as pipeline:
        response = pipeline.run(request)

    assert pipeline._transport.session is None
    assert isinstance(response.http_response.status_code, int)


def test_basic_requests_separate_session(port):

    session = requests.Session()
    request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    transport = RequestsTransport(session=session, session_owner=False)
    with Pipeline(transport, policies=policies) as pipeline:
        response = pipeline.run(request)

    assert transport.session
    assert isinstance(response.http_response.status_code, int)
    transport.close()
    assert transport.session
    transport.session.close()


def test_request_text(port):
    request = HttpRequest("GET", "/", json="foo")

    # In absence of information, everything is JSON (double quote added)
    assert request.content == json.dumps("foo")

    request = HttpRequest("POST", "/", headers={"content-type": "text/whatever"}, content="foo")

    # We want a direct string
    assert request.content == "foo"


def test_httpx_transport_get(port):
    request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    with Pipeline(HttpXTransport(), policies=policies) as pipeline:
        response = pipeline.run(request)

    assert pipeline._transport.client is None
    assert isinstance(response.http_response.status_code, int)


def test_httpx_transport_options(port):

    request = HttpRequest("OPTIONS", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    transport = HttpXTransport()
    with Pipeline(transport, policies=policies) as pipeline:
        response = pipeline.run(request)

    assert pipeline._transport.client is None
    assert isinstance(response.http_response.status_code, int)


def test_httpx_separate_session(port):

    client = httpx.Client()
    request = HttpRequest("GET", "http://localhost:{}/basic/string".format(port))
    policies = [UserAgentPolicy("myusergant")]
    transport = HttpXTransport(client=client, client_owner=False)
    with Pipeline(transport, policies=policies) as pipeline:
        response = pipeline.run(request)

    assert transport.client
    assert isinstance(response.http_response.status_code, int)
    transport.close()
    assert transport.client
    transport.client.close()