Repository navigation
Expand file tree
/
Copy pathtest_web.py
More file actions
556 lines (464 loc) · 18 KB
/
Copy pathtest_web.py
File metadata and controls
556 lines (464 loc) · 18 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2016-02-23
#
"""
test_web2.py
"""
from __future__ import print_function, unicode_literals
import os
import unittest
import urllib2
import json
import shutil
import socket
import sys
import tempfile
from base64 import b64decode
from pprint import pprint
import pytest
import pytest_httpbin
import pytest_localserver
from workflow import web
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
class CaseInsensitiveDictTests(unittest.TestCase):
def setUp(self):
self.data_list = [('Aardvark', 'a'), ('Booty', 'b'), ('Clown', 'c')]
self.data_dict = dict(self.data_list)
def tearDown(self):
pass
def test_init_dict(self):
"""Initialise CaseInsensitiveDict"""
d1 = web.CaseInsensitiveDictionary(self.data_list)
d2 = web.CaseInsensitiveDictionary(self.data_dict)
self.assertEqual(d1, d2)
def test_retrieve(self):
"""CaseInsensitiveDict retrieve values"""
d = web.CaseInsensitiveDictionary(self.data_list)
for k, v in self.data_list:
self.assertEqual(v, d[k])
self.assertEqual(v, d[k.lower()])
self.assertEqual(v, d[k.upper()])
self.assertEqual(v, d[k.title()])
self.assertEqual(v, d.get(k))
self.assertEqual(v, d.get(k.lower()))
self.assertEqual(v, d.get(k.upper()))
self.assertEqual(v, d.get(k.title()))
self.assertTrue(k in d)
self.assertTrue(k.lower() in d)
self.assertTrue(k.upper() in d)
self.assertTrue(k.title() in d)
self.assertTrue(d.get('This is not a key') is None)
self.assertFalse('This is not a key' in d)
def test_set(self):
"""CaseInsensitiveDict set values"""
d = web.CaseInsensitiveDictionary()
for k, v in self.data_list:
self.assertFalse(k in d)
for k, v in self.data_list:
d[k.upper()] = v
for k, v in self.data_list:
self.assertTrue(k in d)
self.assertEqual(d[k], v)
self.assertEqual(d[k.lower()], v)
d2 = {'Dogs': 'd', 'Elephants': 'e'}
for k, v in d2.items():
self.assertFalse(k in d)
self.assertTrue(d.get(k) is None)
d.update(d2)
for k, v in d2.items():
self.assertTrue(k in d)
self.assertTrue(k.upper() in d)
self.assertEqual(d.get(k), v)
def test_iterators(self):
"""CaseInsensitiveDict iterators"""
d = web.CaseInsensitiveDictionary(self.data_dict)
self.assertEqual(sorted(d.keys()), sorted(self.data_dict.keys()))
self.assertEqual(sorted(d.values()), sorted(self.data_dict.values()))
for k in d.iterkeys():
self.assertTrue(k in self.data_dict)
values = self.data_dict.values()
for v in d.itervalues():
self.assertTrue(v in values)
for t in d.iteritems():
self.assertTrue(t in self.data_list)
@pytest_httpbin.use_class_based_httpbin
class WebTests(unittest.TestCase):
def setUp(self):
self.data = {'name': 'My name is Jürgen!',
'address': 'Hürterstr. 42\nEssen'}
self.test_file = os.path.join(DATA_DIR,
'cönfüsed.gif')
self.tempdir = os.path.join(tempfile.gettempdir(),
'web_py.{0:d}.tmp'.format(os.getpid()))
def tearDown(self):
if os.path.exists(self.tempdir):
shutil.rmtree(self.tempdir)
def test_404(self):
"""Non-existant URL raises HTTPError w/ 404"""
url = self.httpbin.url + '/status/404'
r = web.get(url)
self.assertRaises(urllib2.HTTPError, r.raise_for_status)
self.assert_(r.status_code == 404)
def test_follow_redirect(self):
"""Redirects are followed"""
url = self.httpbin.url + '/redirect-to?url=' + self.httpbin.url
r = web.get(url)
self.assertEqual(r.url.rstrip('/'), self.httpbin.url.rstrip('/'))
def test_no_follow_redirect(self):
"""Redirects are not followed"""
url = self.httpbin.url + '/redirect-to?url=' + self.httpbin.url
r = web.get(url, allow_redirects=False)
self.assertNotEquals(r.url, self.httpbin.url)
self.assertRaises(urllib2.HTTPError, r.raise_for_status)
self.assertEqual(r.status_code, 302)
def test_post_form(self):
"""POST Form data"""
url = self.httpbin.url + '/post'
r = web.post(url, data=self.data)
self.assert_(r.status_code == 200)
r.raise_for_status()
form = r.json()['form']
for key in self.data:
self.assert_(form[key] == self.data[key])
def test_post_json(self):
"""POST request with JSON body"""
url = self.httpbin.url + '/post'
headers = {'content-type': 'application/json'}
print('Posting JSON ...')
r = web.post(url, headers=headers, data=json.dumps(self.data))
self.assert_(r.status_code == 200)
data = r.json()
pprint(data)
self.assertEqual(data['headers']['Content-Type'],
'application/json')
for key in self.data:
self.assert_(data['json'][key] == self.data[key])
return
def test_post_without_data(self):
"""POST request without data"""
url = self.httpbin + '/post'
r = web.post(url)
self.assert_(r.status_code == 200)
r.raise_for_status()
def test_timeout(self):
"""Request times out"""
url = self.httpbin.url + '/delay/3'
if sys.version_info < (2, 7):
self.assertRaises(urllib2.URLError, web.get, url, timeout=1)
else:
self.assertRaises(socket.timeout, web.get, url, timeout=1)
def test_encoding(self):
"""HTML is decoded"""
url = self.httpbin.url + '/html'
r = web.get(url)
self.assertEqual(r.encoding, 'utf-8')
self.assert_(isinstance(r.text, unicode))
def test_no_encoding(self):
"""No encoding"""
# Is an image
url = self.httpbin.url + '/bytes/100'
r = web.get(url)
self.assertEqual(r.encoding, None)
self.assert_(isinstance(r.text, str))
def test_xml_encoding(self):
"""XML is decoded"""
# Why doesn't this work with a local httpbin?
# url = self.httpbin.url + '/response-headers'
url = 'http://httpbin.org/response-headers'
params = {'Content-Type': 'text/xml;charset=UTF-8'}
r = web.get(url, params)
r.raise_for_status()
self.assertEqual(r.encoding, 'utf-8')
self.assert_(isinstance(r.text, unicode))
def test_html_encoding(self):
"""HTML is decoded"""
url = self.httpbin.url + '/html'
r = web.get(url)
self.assertEqual(r.encoding, 'utf-8')
self.assert_(isinstance(r.text, unicode))
def test_default_encoding(self):
"""Default encodings for mimetypes"""
# Why doesn't this work with a local httpbin?
# url = self.httpbin.url + '/response-headers'
url = 'http://httpbin.org/response-headers'
# params = {'Content-Type': 'application/json'}
# httpbin returns JSON by default. web.py should automatically
# set `encoding` to UTF-8 when mimetype = 'application/json'
r = web.get(url)
r.raise_for_status()
self.assertEqual(r.encoding, 'utf-8')
self.assert_(isinstance(r.text, unicode))
def test_get_vars(self):
"""GET vars"""
url = self.httpbin.url + '/get'
r = web.get(url, params=self.data)
self.assertEqual(r.status_code, 200)
args = r.json()['args']
for key in self.data:
self.assertEqual(args[key], self.data[key])
def test_auth_succeeds(self):
"""Basic AUTH succeeds"""
url = self.httpbin.url + '/basic-auth/bobsmith/password1'
r = web.get(url, auth=('bobsmith', 'password1'))
self.assertEqual(r.status_code, 200)
data = r.json()
self.assertEqual(data['user'], 'bobsmith')
self.assertTrue(data['authenticated'])
def test_auth_fails(self):
"""Basic AUTH fails"""
url = self.httpbin.url + '/basic-auth/bobsmith/password1'
r = web.get(url, auth=('bobsmith', 'password2'))
self.assertEqual(r.status_code, 401)
self.assertRaises(urllib2.HTTPError, r.raise_for_status)
def test_file_upload(self):
"""File upload"""
url = self.httpbin.url + '/post'
files = {'file': {'filename': 'cönfüsed.gif',
'content': open(self.test_file, 'rb').read(),
'mimetype': 'image/gif',
}}
r = web.post(url, data=self.data, files=files)
self.assertEqual(r.status_code, 200)
data = r.json()
form = data['form']
for key in self.data:
self.assertEqual(self.data[key], form[key])
# image
bindata = data['files']['file']
preamble = 'data:image/gif;base64,'
self.assert_(bindata.startswith(preamble))
bindata = b64decode(bindata[len(preamble):])
self.assertEqual(bindata, open(self.test_file, 'rb').read())
def test_file_upload_without_form_data(self):
"""File upload w/o form data"""
url = self.httpbin.url + '/post'
files = {'file': {'filename': 'cönfüsed.gif',
'content': open(self.test_file, 'rb').read()
}}
r = web.post(url, files=files)
self.assertEqual(r.status_code, 200)
data = r.json()
# image
bindata = data['files']['file']
preamble = 'data:image/gif;base64,'
self.assert_(bindata.startswith(preamble))
bindata = b64decode(bindata[len(preamble):])
self.assertEqual(bindata, open(self.test_file, 'rb').read())
def test_json_encoding(self):
"""JSON decoded correctly"""
url = self.httpbin.url + '/get'
params = {'town': 'münchen'}
r = web.get(url, params)
self.assertEqual(r.status_code, 200)
data = r.json()
self.assertEqual(data['args']['town'], 'münchen')
def test_gzipped_content(self):
"""Gzipped content decoded"""
url = self.httpbin.url + '/gzip'
r = web.get(url)
self.assertEqual(r.status_code, 200)
data = r.json()
self.assertTrue(data.get('gzipped'))
def test_gzipped_iter_content(self):
"""Gzipped iter_content decoded"""
url = self.httpbin.url + '/gzip'
r = web.get(url, stream=True)
self.assertEqual(r.status_code, 200)
data = b''
for b in r.iter_content():
data += b
data = json.loads(data)
self.assertTrue(data.get('gzipped'))
def test_params_added_to_url(self):
"""`params` are added to existing GET args"""
url = self.httpbin.url + '/get?existing=one'
r = web.get(url)
r.raise_for_status()
args = r.json()['args']
print('args=%r' % args)
self.assertEqual(args.get('existing'), 'one')
# Add additional params
params = {'extra': 'two'}
r = web.get(url, params)
r.raise_for_status()
args = r.json()['args']
print('args=%r' % args)
self.assertEqual(args.get('existing'), 'one')
self.assertEqual(args.get('extra'), 'two')
# dP dP
# 88 88
# 88d888b. dP dP d8888P .d8888b. .d8888b. d8888P
# 88' `88 88 88 88 88ooood8 Y8ooooo. 88
# 88. .88 88. .88 dP 88 88. ... 88 88
# 88Y888P' `8888P88 88 dP `88888P' `88888P' dP
# 88 .88
# dP d8888P
fubar_path = os.path.join(DATA_DIR, 'fubar.txt')
fubar_bytes = open(fubar_path).read()
fubar_unicode = unicode(fubar_bytes, 'utf-8')
utf8html_path = os.path.join(DATA_DIR, 'utf8.html')
utf8html_bytes = open(utf8html_path).read()
utf8html_unicode = unicode(utf8html_bytes, 'utf-8')
utf8xml_path = os.path.join(DATA_DIR, 'utf8.xml')
utf8xml_bytes = open(utf8xml_path).read()
utf8xml_unicode = unicode(utf8xml_bytes, 'utf-8')
gifpath = os.path.join(DATA_DIR, 'cönfüsed.gif')
gifbytes = open(gifpath).read()
gifpath_gzip = os.path.join(DATA_DIR, 'cönfüsed.gif.gz')
gifbytes_gzip = open(gifpath_gzip).read()
tempdir = os.path.join(tempfile.gettempdir(),
'web_py.{0}.tmp'.format(os.getpid()))
def test_charset_sniffing(httpserver):
"""Charset sniffing for HTML and XML"""
for data, typ in ((utf8html_bytes, 'text/html'),
(utf8xml_bytes, 'text/xml'),
(utf8xml_bytes, 'application/xml')):
httpserver.serve_content(data, headers={'Content-Type': typ})
r = web.get(httpserver.url)
r.raise_for_status()
assert r.encoding == 'utf-8'
assert isinstance(r.text, unicode)
def test_save_to_path(httpserver):
"""Save directly to file"""
filepath = os.path.join(tempdir, 'fubar.txt')
assert not os.path.exists(tempdir)
assert not os.path.exists(filepath)
httpserver.serve_content(fubar_bytes,
headers={'Content-Type': 'text/plain'})
try:
r = web.get(httpserver.url)
assert r.status_code == 200
r.save_to_path(filepath)
assert os.path.exists(filepath)
data = open(filepath).read()
assert data == fubar_bytes
finally:
if os.path.exists(tempdir):
shutil.rmtree(tempdir)
def test_save_to_path_fails(httpserver):
"""Save to file fails if `content` has been accessed"""
filepath = os.path.join(tempdir, 'fubar.txt')
httpserver.serve_content(fubar_bytes,
headers={'Content-Type': 'text/plain'})
r = web.get(httpserver.url)
r.content
with pytest.raises(RuntimeError):
r.save_to_path(filepath)
if os.path.exists(filepath):
os.unlink(filepath)
def test_iter_content(httpserver):
"""iter_content bytes"""
httpserver.serve_content(fubar_bytes,
headers={'Content-Type': 'text/plain'})
r = web.get(httpserver.url, stream=True)
assert r.status_code == 200
contents = b''
for s in r.iter_content(chunk_size=1):
contents += s
assert contents == fubar_bytes
def test_iter_content_decoded(httpserver):
"""iter_content decoded"""
httpserver.serve_content(fubar_bytes, headers={
'Content-Type':
'text/plain; charset=UTF-8'})
r = web.get(httpserver.url, stream=True)
assert r.status_code == 200
contents = ''
for s in r.iter_content(chunk_size=1, decode_unicode=True):
contents += s
assert contents == fubar_unicode
def test_iter_content_nosniff(httpserver):
"""iter_content doesn't sniff content"""
# Content isn't sniffed when streaming
httpserver.serve_content(utf8html_bytes)
r = web.get(httpserver.url, stream=True)
it = r.iter_content(decode_unicode=True)
for chunk in it:
pass
print('r.encoding=%r' % r.encoding)
assert r.encoding is None
# Pass content-type but no encoding
httpserver.serve_content(utf8html_bytes,
headers={'Content-Type': 'text/html'})
r = web.get(httpserver.url, stream=True)
it = r.iter_content(decode_unicode=True)
for chunk in it:
pass
assert r.encoding == None
# Encoding read from HTTP header
httpserver.serve_content(
utf8html_bytes,
headers={'Content-Type': 'text/html; charset=ascii'})
r = web.get(httpserver.url, stream=True)
for k in r.headers:
print('%r=%r' % (k, r.headers[k]))
it = r.iter_content(decode_unicode=True)
for chunk in it:
pass
assert r.encoding == 'ascii'
# Encoding properly sniffed
httpserver.serve_content(
utf8html_bytes,
headers={'Content-Type': 'text/html'})
r = web.get(httpserver.url)
assert r.encoding == 'utf-8'
def test_iter_content_requires_stream(httpserver):
"""iter_content fails if `stream` is `False`"""
httpserver.serve_content(utf8html_bytes)
r = web.get(httpserver.url)
with pytest.raises(RuntimeError):
r.iter_content(decode_unicode=True)
def test_iter_content_fails_if_content_read(httpserver):
"""iter_content fails if `content` has been read"""
httpserver.serve_content(utf8html_bytes)
r = web.get(httpserver.url, stream=True)
r.content
with pytest.raises(RuntimeError):
r.iter_content(decode_unicode=True)
def test_encoded_content(httpserver):
"""Content decoding"""
httpserver.serve_content(fubar_bytes, headers={
'Content-Type':
'text/plain; charset=UTF-8'})
r = web.get(httpserver.url)
assert r.status_code == 200
assert r.content == fubar_bytes
assert r.text == fubar_unicode
def test_xml_content(httpserver):
"""Correct mimetype for application/xml"""
httpserver.serve_content(utf8xml_bytes, headers={
'Content-Type': 'application/xml'})
r = web.get(httpserver.url, stream=True)
assert r.encoding == 'utf-8'
def test_gzipped_content(httpserver):
"""Gzip encoding"""
httpserver.serve_content(gifbytes,
headers={'Content-Type': 'image/gif'})
r = web.get(httpserver.url)
assert r.status_code == 200
assert r.content == gifbytes
httpserver.serve_content(
gifbytes_gzip,
headers={
'Content-Type': 'image/gif',
'Content-Encoding': 'gzip',
})
# Full response
r = web.get(httpserver.url)
assert r.status_code == 200
assert r.content == gifbytes
# Streamed response
r = web.get(httpserver.url, stream=True)
assert r.status_code == 200
content = b''
for chunk in r.iter_content():
content += chunk
assert content == gifbytes
if __name__ == '__main__': # pragma: no cover
pytest.main([__file__])