Source

vlastic / test / http_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
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
import unittest
import sys
from vlastic.http import *
from vlastic.url import *


class MessageTest(unittest.TestCase):
    """Unit tests for Message class."""

    def setUp(self):
        self.start_line = b"GET /abc/def HTTP/1.1"
        self.headers = [
            (b"Content-Length", b"128"),
            (b"Content-Type", b"text/plain; charset=utf-8")
        ]
        self.body = b"a" * 128
        self.encoding = "utf-8"
        self.msg = Message(
            self.start_line, self.headers, self.body,
            encoding=self.encoding
        )
        self.full_message = self.start_line + b"\r\n" \
                          + b"\r\n".join(n+b": "+v  for n, v in self.headers) \
                          + b"\r\n\r\n" + self.body

    def test_message_iterator(self):
        it = Message._message_iterator([
            self.start_line, b"\r\n",
            self.headers[0][0], b": ", self.headers[0][1], b"\r",
            b"\n" + self.headers[1][0], b": ",
            self.headers[1][1] + b"\r\n\r\n" + b"a" * 63,
            b"\r", b"\n" + b"b" * 63
        ])
        expected = [
            self.start_line + b"\r\n",
            self.headers[0][0] + b": " + self.headers[0][1] + b"\r\n",
            self.headers[1][0] + b": " + self.headers[1][1] + b"\r\n",
            b"\r\n",
            b"a" * 63, b"\r", b"\n" + b"b" * 63
        ]
        self.assertEquals(expected, list(it))

    def test_init_with_headers_dict(self):
        msg = Message(self.start_line, dict(self.headers), self.body)
        self.assertEquals(self.headers, msg.headers)

    def test_init_with_str_headers(self):
        msg = Message(self.start_line, [("Accept", "text/plain")])
        self.assertEquals([(b"Accept", b"text/plain")], msg.headers)

    def test_init_with_start_line_tuple(self):
        msg = Message(("GET", "/abc/def", "HTTP/1.1"), self.headers, self.body)
        self.assertEquals(self.start_line, msg.start_line)

    def test_init_with_full_message(self):
        msg = Message(self.full_message, encoding=self.encoding)
        self.assertEquals(self.start_line, msg.start_line)
        self.assertEquals(self.headers, msg.headers)
        self.assertEquals(self.body, b"".join(msg.body))
        self.assertEquals(self.encoding, msg.encoding)

    def test_init_with_body_iterator(self):
        i = [0]
        def get_body():
            i[0] += 1; yield b"1"
            i[0] += 1; yield b"2"
            i[0] += 1; yield b"3"
            i[0] += 1
        msg = Message(self.start_line, self.headers, get_body())
        self.assertEquals(0, i[0])
        self.assertEquals(b"1", msg.body.__next__())
        self.assertEquals(1, i[0])
        self.assertEquals(b"2", msg.body.__next__())
        self.assertEquals(2, i[0])
        self.assertEquals(b"3", msg.body.__next__())
        self.assertEquals(3, i[0])
        self.assertRaises(StopIteration, msg.body.__next__)
        self.assertEquals(4, i[0])

    def test_init_with_full_message_iterator(self):
        i = [0]
        def get_full_message():
            i[0] += 1; yield b"GET / HTTP"
            i[0] += 1; yield b"/1.1\r\nHost: dahlia"
            i[0] += 1; yield b".kr\r"
            i[0] += 1; yield b"\n\r\nabc"
            i[0] += 1; yield b"=def&g"
            i[0] += 1; yield b"=h"
            i[0] += 1
        full_message = get_full_message()
        self.assertEquals(0, i[0])
        msg = Message(full_message)
        self.assertEquals(4, i[0])
        self.assertEquals(b"abc", msg.body.__next__())
        self.assertEquals(4, i[0])
        self.assertEquals(b"=def&g", msg.body.__next__())
        self.assertEquals(5, i[0])
        self.assertEquals(b"=h", msg.body.__next__())
        self.assertEquals(6, i[0])
        self.assertRaises(StopIteration, msg.body.__next__)
        self.assertEquals(7, i[0])

    def test_encoding(self):
        self.assertEquals(self.encoding, self.msg.encoding)
        self.assertEquals(
            sys.getdefaultencoding(),
            Message(self.start_line, [], b"").encoding
        )

    def test_start_line(self):
        self.assertEquals(self.start_line, self.msg.start_line)

    def test_headers(self):
        self.assertEquals(self.headers, self.msg.headers)
        self.assertTrue(isinstance(self.msg.headers, list))

    def test_body(self):
        self.assertEquals(self.body, b"".join(self.msg.body))

    def test_body_sequence(self):
        msg = Message(
            self.start_line, self.headers,
            [b"1", b"2", b"3"]
        )
        self.assertEquals(b"123", b"".join(msg.body))

    def test_contains_bytes(self):
        self.assertTrue(b"Content-Length" in self.msg)
        self.assertTrue(b"content-LENGTH" in self.msg)
        self.assertFalse(b"Connection" in self.msg)

    def test_contains_str(self):
        self.assertTrue("Content-Length" in self.msg)
        self.assertTrue("content-LENGTH" in self.msg)
        self.assertFalse("Connection" in self.msg)

    def test_contains_typeerror(self):
        self.assertRaises(TypeError, lambda: 1 in self.msg)

    def test_getitem_bytes(self):
        self.assertEquals(b"128", self.msg[b"Content-Length"])
        self.assertEquals(b"128", self.msg[b"content-LENGTH"])
        self.assertRaises(KeyError, lambda: self.msg[b"Connection"])

    def test_getitem_str(self):
        self.assertEquals("128", self.msg["Content-Length"])
        self.assertEquals("128", self.msg["content-LENGTH"])
        self.assertRaises(KeyError, lambda: self.msg["Connection"])

    def test_getitem_typeerror(self):
        self.assertRaises(TypeError, lambda: self.msg[1])

    def test_setitem_append(self):
        msg = Message(b"", [], b"")
        msg[b"Accept-Language"] = b"ko; q=1.0, en; q=0.8"
        self.assertEquals(
            [(b"Accept-Language", b"ko; q=1.0, en; q=0.8")],
            msg.headers
        )
        msg["Accept"] = "*"
        self.assertEquals(
            [(b"Accept-Language", b"ko; q=1.0, en; q=0.8"),
             (b"Accept", b"*")],
            msg.headers
        )

    def test_setitem_replace(self):
        msg = Message(b"", [(b"Vary", b"Accept")], b"")
        msg[b"VARY"] = b"Accept, Accept-Language"
        self.assertEquals(
            [(b"VARY", b"Accept, Accept-Language")],
            msg.headers
        )
        msg["vary"] = "Accept-Encoding"
        self.assertEquals([(b"vary", b"Accept-Encoding")], msg.headers)

    def test_setitem_typeerror(self):
        def msg_setitem():
            self.msg[1] = b"123"
        self.assertRaises(TypeError, msg_setitem)
        def msg_setitem():
            self.msg[b"abc"] = 123
        self.assertRaises(TypeError, msg_setitem)

    def test_str(self):
        self.assertEquals(
            self.full_message.decode(self.encoding),
            str(self.msg)
        )

    def test_bytes(self):
        self.assertEquals(self.full_message, bytes(self.msg))

    def test_repr(self):
        self.assertEquals(
            "vlastic.http.Message(b'GET /abc/def HTTP/1.1', ...)",
            repr(self.msg)
        )


class RequestPathTest(unittest.TestCase):
    """Unit tests for RequestPath class."""

    def setUp(self):
        self.path = RequestPath("/path//entry/1")

    def test_str(self):
        self.assertEquals("/path/entry/1", str(self.path))

    def test_iter(self):
        self.assertEquals(["path", "entry", "1"], list(self.path))

    def test_front_segments(self):
        self.assertEquals([], self.path.front_segments())
        next(self.path)
        self.assertEquals(["path"], self.path.front_segments())
        next(self.path)
        self.assertEquals(["path", "entry"], self.path.front_segments())

    def test_current_segment(self):
        next(self.path)
        self.assertEquals("entry", self.path.current_segment())


class RequestTest(unittest.TestCase):
    """Unit tests for Request class."""

    def setUp(self):
        self.setup_message(b"GET", b"/?a=1&b=2")

    def setup_message(self, method, path, body=b""):
        self.method = method
        self.path = path
        self.protocol = b"HTTP/1.1"
        self.start_line = b" ".join((self.method, self.path, self.protocol))
        self.headers = [
            (b"Accept", b"image/gif, image/jpeg, image/pjpeg"),
            (b"Referer", b"dahlia.kr"),
            (b"Accept-Language", b"ko"),
            (b"Accept-Encoding", b"gzip, deflate"),
            (b"Host", b"kldp.org")
        ]
        self.body = body
        headerstr = b"\r\n".join(n + b": " + v for n, v in self.headers)
        self.full_message = self.start_line + b"\r\n" + headerstr \
                          + b"\r\n\r\n" + body

    def test_init_full_message(self):
        req = Request(self.full_message)
        self.assertEquals("GET", req.method)
        self.assertEquals("GET", req.verb)
        self.assertEquals("/", str(req.path))
        self.assertTrue(isinstance(req.query, QueryString))
        self.assertEquals("a=1&b=2", str(req.query))
        self.assertEquals(self.headers, req.headers)

    def test_init_each(self):
        req = Request(self.start_line, self.headers)
        self.assertEquals("GET", req.method)
        self.assertEquals("GET", req.verb)
        self.assertEquals("/", str(req.path))
        self.assertTrue(isinstance(req.query, QueryString))
        self.assertEquals("a=1&b=2", str(req.query))
        self.assertEquals(self.headers, req.headers)
        req = Request((self.method, self.path, self.protocol), self.headers)
        self.assertEquals("GET", req.method)
        self.assertEquals("/", str(req.path))
        self.assertTrue(isinstance(req.query, QueryString))
        self.assertEquals("a=1&b=2", str(req.query))
        self.assertEquals(self.headers, req.headers)

    def test_post(self):
        self.setup_message(b"POST", b"/", b"a=1&b=2")
        req = Request(self.start_line, self.headers, self.body)
        self.assertEquals("POST", req.method)
        self.assertEquals("POST", req.verb)
        self.assertEquals("/", str(req.path))
        self.assertTrue(isinstance(req.query, QueryString))
        self.assertEquals("", str(req.query))
        self.assertTrue(isinstance(req.data, QueryString))
        self.assertEquals("a=1&b=2", str(req.data))
        self.assertEquals(self.headers, req.headers)

    def test_accept(self):
        req = Request(self.start_line, self.headers)
        self.assertTrue(isinstance(req.accept, NegotiativeHeader))
        self.assertTrue("image/gif" in req.accept)
        self.assertTrue("image/jpeg" in req.accept)
        self.assertTrue("image/pjpeg" in req.accept)

    def test_accept_none(self):
        req = Request(self.start_line, {})
        self.assertEquals(id(None), id(req.accept))


class ResponseTest(unittest.TestCase):
    """Unit tests for Response class."""

    def test_init_full_message(self):
        res = Response(b"HTTP/1.1 404 Not Found\r\n\r\nabcde")
        self.assertEquals(404, res.status_code)
        self.assertEquals("Not Found", res.reason_phrase)

    def test_init_each(self):
        res = Response((b"HTTP/1.1", 200, b"OK"), {}, b"abcde")
        self.assertEquals(200, res.status_code)
        self.assertEquals("OK", res.reason_phrase)


class ErrorResponseTest(unittest.TestCase):
    """Unit tests for ErrorResponse class."""

    def setUp(self):
        self.status_code, self.reason_phrase = 400, "Bad Request"
        self.res = ErrorResponse(self.status_code, self.reason_phrase)

    def test_type(self):
        self.assertTrue(isinstance(self.res, Response))

    def test_status_code(self):
        self.assertEquals(self.status_code, self.res.status_code)

    def test_reason_phrase(self):
        self.assertEquals(self.reason_phrase, self.res.reason_phrase)

    def test_raises(self):
        def throw():
            raise self.res
        self.assertRaises(type(self.res), throw)



class NotFoundErrorTest(ErrorResponseTest):
    """Unit tests for NotFoundError (404) class."""

    def setUp(self):
        self.status_code, self.reason_phrase = 404, "Not Found"
        self.res = NotFoundError()


class MethodNotAllowedErrorTest(ErrorResponseTest):
    """Unit tests for MethodNotAllowedError (405) class."""

    def setUp(self):
        self.status_code, self.reason_phrase = 405, "Method Not Allowed"
        self.res = MethodNotAllowedError()


class NotAcceptableErrorTest(ErrorResponseTest):
    """Unit tests for NotAcceptableError (406) class."""

    def setUp(self):
        self.status_code, self.reason_phrase = 406, "Not Acceptable"
        self.res = NotAcceptableError()


class NegotiativeHeaderTest(unittest.TestCase):
    """Unit tests for NegotiativeHeader class."""

    def setUp(self):
        self.encoding = "utf-8"
        self.header = b"gzip; q=0.5, identity, *; q=0"
        self.nh = NegotiativeHeader(self.header)

    def test_with_level(self):
        header = b"gzip; level=1; q=0.5, identity, *; version=2; q=0"
        nh = NegotiativeHeader(header)
        self.assertEquals(["gzip", "identity"], list(self.nh))

    def test_init(self):
        self.assertEquals(self.header, self.nh.bytes_header)

    def test_bytes(self):
        self.assertEquals(self.header, bytes(self.nh))

    def test_repr(self):
        self.assertEquals("gzip; q=0.5, identity; q=1, *; q=0", self.nh.__repr__())

    def test_list(self):
        self.assertEquals(["gzip", "identity"], list(self.nh))

    def test_str(self):
        self.assertEquals(self.header.decode(self.encoding), str(self.nh))

    def test_contain(self):
        self.assertEquals(True, "gzip" in self.nh)
        self.assertEquals(True, "identity" in self.nh)
        self.assertEquals(False, "compress" in self.nh)

    def test_first_match(self):
        self.assertEquals("gzip", self.nh.first_match(["gzip", "identity"]))

    def test_best_match(self):
        self.assertEquals("identity", self.nh.best_match(["gzip", "identity"]))

    def test_all_matches(self):
        self.assertEquals(
            ["gzip", "identity"],
            self.nh.all_matches(["gzip", "identity"]))

    def test_best_matches(self):
        self.assertEquals(["identity", "gzip"], self.nh.best_matches(
            ["gzip", "identity"]))


from vlastic.http import LanguageComparator

class LanguageComparatorTest(unittest.TestCase):
    """Unit tests for LanguageComparator class."""

    def test_unpack_language(self):
        language_unpacker = LanguageComparator.unpack_lang_country
        self.assertEquals(("en", "US"), language_unpacker("en-US"))
        self.assertEquals(("en", ''), language_unpacker("en"))

    def test_lang_indexes(self):
        language_indexer = LanguageComparator.lang_indexes
        self.assertEquals(
            [0, 1], language_indexer(["en", "en", "es", "pt", "ko"], "en"))


class NegotiativeLanguageHeaderTest(unittest.TestCase):
    """Unit tests for NegotiativeLanguageHeader class."""

    def setUp(self):
        self.encoding = "utf-8"
        self.header = b"es; q=0.5, pt-BR; q=0.7, ko-KR"
        self.nlh = NegotiativeLanguageHeader(self.header)

    def test_init(self):
        self.assertEquals(self.header, self.nlh.bytes_header)
        self.assertEquals(
            [("es", "", 0.5), ("pt", "BR", 0.7), ("ko", "KR", 1.0)],
            self.nlh.header)

    def test_bytes(self):
        self.assertEquals(self.header, bytes(self.nlh))

    def test_str(self):
        self.assertEquals(self.header.decode(self.encoding), str(self.nlh))

    def test_repr(self):
        self.assertEquals(
            "es; q=0.5, pt-BR; q=0.7, ko-KR; q=1",
            self.nlh.__repr__())

    def test_best_matches(self):
        self.assertEquals(
            ["ko", "pt", "en-US", "en-UK",],
            self.nlh.best_matches(["en-US", "en-UK", "pt", "ko"]))
        
        nlh = NegotiativeLanguageHeader(
            b"en-US; q=0.2, en-UK; q=0.1, es; q=0.5, pt-BR; q=0.7, ko-KR")
        self.assertEquals(
            ["en-US", "en-UK", "ko", "pt"],
            nlh.best_matches(["en-UK", "en-US", "ko", "pt"]))
        self.assertEquals(
            ["en-US", "en-UK", "ko", "pt"],
            nlh.best_matches(["en-UK", "pt", "en-US", "ko"]))