/
test_http.py
373 lines (309 loc) · 15.1 KB
/
test_http.py
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
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import json
import os
import unittest
from collections import OrderedDict
from unittest import mock
import pytest
import requests
import requests_mock
import tenacity
from parameterized import parameterized
from airflow.exceptions import AirflowException
from airflow.models import Connection
from airflow.providers.http.hooks.http import HttpHook
def get_airflow_connection(unused_conn_id=None):
return Connection(conn_id='http_default', conn_type='http', host='test:8080/', extra='{"bareer": "test"}')
def get_airflow_connection_with_port(unused_conn_id=None):
return Connection(conn_id='http_default', conn_type='http', host='test.com', port=1234)
class TestHttpHook(unittest.TestCase):
"""Test get, post and raise_for_status"""
def setUp(self):
session = requests.Session()
adapter = requests_mock.Adapter()
session.mount('mock', adapter)
self.get_hook = HttpHook(method='GET')
self.get_lowercase_hook = HttpHook(method='get')
self.post_hook = HttpHook(method='POST')
@requests_mock.mock()
def test_raise_for_status_with_200(self, m):
m.get('http://test:8080/v1/test', status_code=200, text='{"status":{"status": 200}}', reason='OK')
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
resp = self.get_hook.run('v1/test')
assert resp.text == '{"status":{"status": 200}}'
@requests_mock.mock()
@mock.patch('requests.Session')
@mock.patch('requests.Request')
def test_get_request_with_port(self, mock_requests, request_mock, mock_session):
from requests.exceptions import MissingSchema
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
expected_url = 'http://test.com:1234/some/endpoint'
for endpoint in ['some/endpoint', '/some/endpoint']:
try:
self.get_hook.run(endpoint)
except MissingSchema:
pass
request_mock.assert_called_once_with(
mock.ANY, expected_url, headers=mock.ANY, params=mock.ANY
)
request_mock.reset_mock()
@requests_mock.mock()
def test_get_request_do_not_raise_for_status_if_check_response_is_false(self, m):
m.get(
'http://test:8080/v1/test',
status_code=404,
text='{"status":{"status": 404}}',
reason='Bad request',
)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
resp = self.get_hook.run('v1/test', extra_options={'check_response': False})
assert resp.text == '{"status":{"status": 404}}'
@requests_mock.mock()
def test_hook_contains_header_from_extra_field(self, mock_requests):
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
expected_conn = get_airflow_connection()
conn = self.get_hook.get_conn()
assert dict(conn.headers, **json.loads(expected_conn.extra)) == conn.headers
assert conn.headers.get('bareer') == 'test'
@requests_mock.mock()
@mock.patch('requests.Request')
def test_hook_with_method_in_lowercase(self, mock_requests, request_mock):
from requests.exceptions import InvalidURL, MissingSchema
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
data = "test params"
try:
self.get_lowercase_hook.run('v1/test', data=data)
except (MissingSchema, InvalidURL):
pass
request_mock.assert_called_once_with(mock.ANY, mock.ANY, headers=mock.ANY, params=data)
@requests_mock.mock()
def test_hook_uses_provided_header(self, mock_requests):
conn = self.get_hook.get_conn(headers={"bareer": "newT0k3n"})
assert conn.headers.get('bareer') == "newT0k3n"
@requests_mock.mock()
def test_hook_has_no_header_from_extra(self, mock_requests):
conn = self.get_hook.get_conn()
assert conn.headers.get('bareer') is None
@requests_mock.mock()
def test_hooks_header_from_extra_is_overridden(self, mock_requests):
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
conn = self.get_hook.get_conn(headers={"bareer": "newT0k3n"})
assert conn.headers.get('bareer') == 'newT0k3n'
@requests_mock.mock()
def test_post_request(self, mock_requests):
mock_requests.post(
'http://test:8080/v1/test', status_code=200, text='{"status":{"status": 200}}', reason='OK'
)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
resp = self.post_hook.run('v1/test')
assert resp.status_code == 200
@requests_mock.mock()
def test_post_request_with_error_code(self, mock_requests):
mock_requests.post(
'http://test:8080/v1/test',
status_code=418,
text='{"status":{"status": 418}}',
reason='I\'m a teapot',
)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
with pytest.raises(AirflowException):
self.post_hook.run('v1/test')
@requests_mock.mock()
def test_post_request_do_not_raise_for_status_if_check_response_is_false(self, mock_requests):
mock_requests.post(
'http://test:8080/v1/test',
status_code=418,
text='{"status":{"status": 418}}',
reason='I\'m a teapot',
)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
resp = self.post_hook.run('v1/test', extra_options={'check_response': False})
assert resp.status_code == 418
@mock.patch('airflow.providers.http.hooks.http.requests.Session')
def test_retry_on_conn_error(self, mocked_session):
retry_args = dict(
wait=tenacity.wait_none(),
stop=tenacity.stop_after_attempt(7),
retry=tenacity.retry_if_exception_type(requests.exceptions.ConnectionError),
)
def send_and_raise(unused_request, **kwargs):
raise requests.exceptions.ConnectionError
mocked_session().send.side_effect = send_and_raise
# The job failed for some reason
with pytest.raises(tenacity.RetryError):
self.get_hook.run_with_advanced_retry(endpoint='v1/test', _retry_args=retry_args)
assert self.get_hook._retry_obj.stop.max_attempt_number + 1 == mocked_session.call_count
@requests_mock.mock()
def test_run_with_advanced_retry(self, m):
m.get('http://test:8080/v1/test', status_code=200, reason='OK')
retry_args = dict(
wait=tenacity.wait_none(),
stop=tenacity.stop_after_attempt(3),
retry=tenacity.retry_if_exception_type(Exception),
reraise=True,
)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
response = self.get_hook.run_with_advanced_retry(endpoint='v1/test', _retry_args=retry_args)
assert isinstance(response, requests.Response)
def test_header_from_extra_and_run_method_are_merged(self):
def run_and_return(unused_session, prepped_request, unused_extra_options, **kwargs):
return prepped_request
# The job failed for some reason
with mock.patch(
'airflow.providers.http.hooks.http.HttpHook.run_and_check', side_effect=run_and_return
):
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
prepared_request = self.get_hook.run('v1/test', headers={'some_other_header': 'test'})
actual = dict(prepared_request.headers)
assert actual.get('bareer') == 'test'
assert actual.get('some_other_header') == 'test'
@mock.patch('airflow.providers.http.hooks.http.HttpHook.get_connection')
def test_http_connection(self, mock_get_connection):
conn = Connection(conn_id='http_default', conn_type='http', host='localhost', schema='http')
mock_get_connection.return_value = conn
hook = HttpHook()
hook.get_conn({})
assert hook.base_url == 'http://localhost'
@mock.patch('airflow.providers.http.hooks.http.HttpHook.get_connection')
def test_https_connection(self, mock_get_connection):
conn = Connection(conn_id='http_default', conn_type='http', host='localhost', schema='https')
mock_get_connection.return_value = conn
hook = HttpHook()
hook.get_conn({})
assert hook.base_url == 'https://localhost'
@mock.patch('airflow.providers.http.hooks.http.HttpHook.get_connection')
def test_host_encoded_http_connection(self, mock_get_connection):
conn = Connection(conn_id='http_default', conn_type='http', host='http://localhost')
mock_get_connection.return_value = conn
hook = HttpHook()
hook.get_conn({})
assert hook.base_url == 'http://localhost'
@mock.patch('airflow.providers.http.hooks.http.HttpHook.get_connection')
def test_host_encoded_https_connection(self, mock_get_connection):
conn = Connection(conn_id='http_default', conn_type='http', host='https://localhost')
mock_get_connection.return_value = conn
hook = HttpHook()
hook.get_conn({})
assert hook.base_url == 'https://localhost'
def test_method_converted_to_uppercase_when_created_in_lowercase(self):
assert self.get_lowercase_hook.method == 'GET'
@mock.patch('airflow.providers.http.hooks.http.HttpHook.get_connection')
def test_connection_without_host(self, mock_get_connection):
conn = Connection(conn_id='http_default', conn_type='http')
mock_get_connection.return_value = conn
hook = HttpHook()
hook.get_conn({})
assert hook.base_url == 'http://'
@parameterized.expand(
[
'GET',
'POST',
]
)
@requests_mock.mock()
def test_json_request(self, method, mock_requests):
obj1 = {'a': 1, 'b': 'abc', 'c': [1, 2, {"d": 10}]}
def match_obj1(request):
return request.json() == obj1
mock_requests.request(method=method, url='//test:8080/v1/test', additional_matcher=match_obj1)
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
# will raise NoMockAddress exception if obj1 != request.json()
HttpHook(method=method).run('v1/test', json=obj1)
@mock.patch('airflow.providers.http.hooks.http.requests.Session.send')
def test_verify_set_to_true_by_default(self, mock_session_send):
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
self.get_hook.run('/some/endpoint')
mock_session_send.assert_called_once_with(
mock.ANY,
allow_redirects=True,
cert=None,
proxies=OrderedDict(),
stream=False,
timeout=None,
verify=True,
)
@mock.patch('airflow.providers.http.hooks.http.requests.Session.send')
@mock.patch.dict(os.environ, {"REQUESTS_CA_BUNDLE": "/tmp/test.crt"})
def test_requests_ca_bundle_env_var(self, mock_session_send):
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
self.get_hook.run('/some/endpoint')
mock_session_send.assert_called_once_with(
mock.ANY,
allow_redirects=True,
cert=None,
proxies=OrderedDict(),
stream=False,
timeout=None,
verify='/tmp/test.crt',
)
@mock.patch('airflow.providers.http.hooks.http.requests.Session.send')
@mock.patch.dict(os.environ, {"REQUESTS_CA_BUNDLE": "/tmp/test.crt"})
def test_verify_respects_requests_ca_bundle_env_var(self, mock_session_send):
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
self.get_hook.run('/some/endpoint', extra_options={'verify': True})
mock_session_send.assert_called_once_with(
mock.ANY,
allow_redirects=True,
cert=None,
proxies=OrderedDict(),
stream=False,
timeout=None,
verify='/tmp/test.crt',
)
@mock.patch('airflow.providers.http.hooks.http.requests.Session.send')
@mock.patch.dict(os.environ, {"REQUESTS_CA_BUNDLE": "/tmp/test.crt"})
def test_verify_false_parameter_overwrites_set_requests_ca_bundle_env_var(self, mock_session_send):
with mock.patch(
'airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection_with_port
):
self.get_hook.run('/some/endpoint', extra_options={'verify': False})
mock_session_send.assert_called_once_with(
mock.ANY,
allow_redirects=True,
cert=None,
proxies=OrderedDict(),
stream=False,
timeout=None,
verify=False,
)
@requests_mock.mock()
def test_connection_success(self, m):
m.get('http://test:8080', status_code=200, json={"status": {"status": 200}}, reason='OK')
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
status, msg = self.get_hook.test_connection()
assert status is True
assert msg == 'Connection successfully tested'
@requests_mock.mock()
def test_connection_failure(self, m):
m.get('http://test:8080', status_code=500, json={"message": "internal server error"}, reason='NOT_OK')
with mock.patch('airflow.hooks.base.BaseHook.get_connection', side_effect=get_airflow_connection):
status, msg = self.get_hook.test_connection()
assert status is False
assert msg == '500:NOT_OK'
send_email_test = mock.Mock()