forked from iotaledger/iota.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadapter_test.py
419 lines (331 loc) · 12.1 KB
/
adapter_test.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
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
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
import json
import socket
from typing import Text
from unittest import TestCase
import requests
from iota import BadApiResponse, InvalidUri, TryteString
from iota.adapter import API_VERSION, HttpAdapter, MockAdapter, resolve_adapter
from six import BytesIO, text_type
from test import mock
class ResolveAdapterTestCase(TestCase):
"""
Unit tests for :py:func:`resolve_adapter`.
"""
def test_adapter_instance(self):
"""
Resolving an adapter instance.
"""
adapter = MockAdapter()
self.assertIs(resolve_adapter(adapter), adapter)
def test_http(self):
"""
Resolving a valid ``http://`` URI.
"""
adapter = resolve_adapter('http://localhost:14265/')
self.assertIsInstance(adapter, HttpAdapter)
def test_https(self):
"""
Resolving a valid ``https://`` URI.
"""
adapter = resolve_adapter('https://localhost:14265/')
self.assertIsInstance(adapter, HttpAdapter)
def test_missing_protocol(self):
"""
The URI does not include a protocol.
"""
with self.assertRaises(InvalidUri):
resolve_adapter('localhost:14265')
def test_unknown_protocol(self):
"""
The URI references a protocol that has no associated adapter.
"""
with self.assertRaises(InvalidUri):
resolve_adapter('foobar://localhost:14265')
def create_http_response(content, status=200):
# type: (Text, int) -> requests.Response
"""
Creates an HTTP Response object for a test.
References:
- :py:meth:`requests.adapters.HTTPAdapter.build_response`
"""
response = requests.Response()
response.encoding = 'utf-8'
response.status_code = status
response.raw = BytesIO(content.encode('utf-8'))
return response
class HttpAdapterTestCase(TestCase):
def test_http(self):
"""
Configuring HttpAdapter using a valid ``http://`` URI.
"""
uri = 'http://localhost:14265/'
adapter = HttpAdapter(uri)
self.assertEqual(adapter.node_url, uri)
def test_https(self):
"""
Configuring HttpAdapter using a valid ``https://`` URI.
"""
uri = 'https://localhost:14265/'
adapter = HttpAdapter(uri)
self.assertEqual(adapter.node_url, uri)
def test_ipv4_address(self):
"""
Configuring an HttpAdapter using an IPv4 address.
"""
uri = 'http://127.0.0.1:8080/'
adapter = HttpAdapter(uri)
self.assertEqual(adapter.node_url, uri)
def test_configure_error_missing_protocol(self):
"""
Forgetting to add the protocol to the URI.
"""
with self.assertRaises(InvalidUri):
HttpAdapter.configure('localhost:14265')
def test_configure_error_invalid_protocol(self):
"""
Attempting to configure HttpAdapter with unsupported protocol.
"""
with self.assertRaises(InvalidUri):
HttpAdapter.configure('ftp://localhost:14265/')
def test_configure_error_empty_host(self):
"""
Attempting to configure HttpAdapter with empty host.
"""
with self.assertRaises(InvalidUri):
HttpAdapter.configure('http://:14265')
def test_configure_error_non_numeric_port(self):
"""
Attempting to configure HttpAdapter with non-numeric port.
"""
with self.assertRaises(InvalidUri):
HttpAdapter.configure('http://localhost:iota/')
def test_configure_error_udp(self):
"""
UDP is not a valid protocol for ``HttpAdapter``.
"""
with self.assertRaises(InvalidUri):
HttpAdapter.configure('udp://localhost:14265')
def test_success_response(self):
"""
Simulates sending a command to the node and getting a success
response.
"""
adapter = HttpAdapter('http://localhost:14265')
payload = {'command': 'helloWorld'}
expected_result = {'message': 'Hello, IOTA!'}
mocked_response = create_http_response(json.dumps(expected_result))
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
result = adapter.send_request(payload)
self.assertEqual(result, expected_result)
# https://github.com/iotaledger/iota.lib.py/issues/84
mocked_sender.assert_called_once_with(
headers = {
'Content-type': 'application/json',
'X-IOTA-API-Version': API_VERSION,
},
payload = json.dumps(payload),
url = adapter.node_url,
)
def test_error_response(self):
"""
Simulates sending a command to the node and getting an error
response.
"""
adapter = HttpAdapter('http://localhost:14265')
error_message = 'Command \u0027helloWorld\u0027 is unknown'
mocked_response = create_http_response(
status = 400,
content = json.dumps({
'error': error_message,
'duration': 42,
}),
)
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'400 response from node: {error}'.format(error=error_message),
)
def test_exception_response(self):
"""
Simulates sending a command to the node and getting an exception
response.
"""
adapter = HttpAdapter('http://localhost:14265')
error_message = 'java.lang.ArrayIndexOutOfBoundsException: 4'
mocked_response = create_http_response(
status = 500,
content = json.dumps({
'exception': error_message,
'duration': 16,
}),
)
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'500 response from node: {error}'.format(error=error_message),
)
def test_non_200_status(self):
"""
The node sends back a non-200 response that we don't know how to
handle.
"""
adapter = HttpAdapter('http://localhost')
decoded_response = {'message': 'Request limit exceeded.'}
mocked_response = create_http_response(
status = 429,
content = json.dumps(decoded_response),
)
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'429 response from node: {decoded}'.format(decoded=decoded_response),
)
def test_empty_response(self):
"""
The response is empty.
"""
adapter = HttpAdapter('http://localhost:14265')
mocked_response = create_http_response('')
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'Empty 200 response from node.',
)
def test_non_json_response(self):
"""
The response is not JSON.
"""
adapter = HttpAdapter('http://localhost:14265')
invalid_response = 'EHLO iotatoken.com' # Erm...
mocked_response = create_http_response(invalid_response)
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'Non-JSON 200 response from node: ' + invalid_response,
)
def test_non_object_response(self):
"""
The response is valid JSON, but it's not an object.
"""
adapter = HttpAdapter('http://localhost:14265')
invalid_response = ['message', 'Hello, IOTA!']
mocked_response = create_http_response(json.dumps(invalid_response))
mocked_sender = mock.Mock(return_value=mocked_response)
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
with self.assertRaises(BadApiResponse) as context:
adapter.send_request({'command': 'helloWorld'})
self.assertEqual(
text_type(context.exception),
'Malformed 200 response from node: {response!r}'.format(
response = invalid_response,
),
)
@mock.patch('iota.adapter.request')
def test_default_timeout(self, request_mock):
# create dummy response
request_mock.return_value = mock.Mock(text='{ "dummy": "payload"}', status_code=200)
# create adapter
mock_payload = {'dummy': 'payload'}
adapter = HttpAdapter('http://localhost:14265')
# test with default timeout
adapter.send_request(payload=mock_payload)
_, kwargs = request_mock.call_args
self.assertEqual(kwargs['timeout'], socket.getdefaulttimeout())
@mock.patch('iota.adapter.request')
def test_instance_attribute_timeout(self, request_mock):
# create dummy response
request_mock.return_value = mock.Mock(text='{ "dummy": "payload"}', status_code=200)
# create adapter
mock_payload = {'dummy': 'payload'}
adapter = HttpAdapter('http://localhost:14265')
# test with explicit attribute
adapter.timeout = 77
adapter.send_request(payload=mock_payload)
_, kwargs = request_mock.call_args
self.assertEqual(kwargs['timeout'], 77)
@mock.patch('iota.adapter.request')
def test_argument_overriding_attribute_timeout(self, request_mock):
# create dummy response
request_mock.return_value = mock.Mock(text='{ "dummy": "payload"}', status_code=200)
# create adapter
mock_payload = {'dummy': 'payload'}
adapter = HttpAdapter('http://localhost:14265')
# test with timeout in kwargs
adapter.timeout = 77
adapter.send_request(payload=mock_payload, timeout=88)
_, kwargs = request_mock.call_args
self.assertEqual(kwargs['timeout'], 88)
@mock.patch('iota.adapter.request')
def test_argument_overriding_init_timeout(self, request_mock):
# create dummy response
request_mock.return_value = mock.Mock(text='{ "dummy": "payload"}', status_code=200)
# create adapter
mock_payload = {'dummy': 'payload'}
adapter = HttpAdapter('http://localhost:14265')
# test with timeout at adapter creation
adapter = HttpAdapter('http://localhost:14265', timeout=99)
adapter.send_request(payload=mock_payload)
_, kwargs = request_mock.call_args
self.assertEqual(kwargs['timeout'], 99)
# noinspection SpellCheckingInspection
@staticmethod
def test_trytes_in_request():
"""
Sending a request that includes trytes.
"""
adapter = HttpAdapter('http://localhost:14265')
# Response is not important for this test; we just need to make
# sure that the request is converted correctly.
mocked_sender = mock.Mock(return_value=create_http_response('{}'))
# noinspection PyUnresolvedReferences
with mock.patch.object(adapter, '_send_http_request', mocked_sender):
adapter.send_request({
'command': 'helloWorld',
'trytes': [
TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA'),
TryteString(
b'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA',
),
],
})
mocked_sender.assert_called_once_with(
url = adapter.node_url,
payload = json.dumps({
'command': 'helloWorld',
# Tryte sequences are converted to strings for transport.
'trytes': [
'RBTC9D9DCDQAEASBYBCCKBFA',
'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA',
],
}),
headers = {
'Content-type': 'application/json',
'X-IOTA-API-Version': API_VERSION,
},
)