PageRenderTime 21ms CodeModel.GetById 12ms app.highlight 6ms RepoModel.GetById 2ms app.codeStats 0ms

/tests/web/test_gzip.py

https://bitbucket.org/prologic/circuits/
Python | 76 lines | 46 code | 29 blank | 1 comment | 0 complexity | 5418ada8f0e0b3f90d505d29b1447784 MD5 | raw file
 1#!/usr/bin/env python
 2
 3
 4from pytest import fixture
 5
 6
 7from os import path
 8from io import BytesIO
 9
10
11from circuits.web import Controller
12from circuits.web.tools import gzip
13from circuits import handler, Component
14
15
16from .conftest import DOCROOT
17from .helpers import build_opener, Request
18
19
20class Gzip(Component):
21
22    channel = "web"
23
24    @handler("response", priority=1.0)
25    def _on_response(self, event, *args, **kwargs):
26        event[0] = gzip(event[0])
27
28
29class Root(Controller):
30
31    def index(self):
32        return "Hello World!"
33
34
35@fixture(scope="module")
36def gziptool(request, webapp):
37    gziptool = Gzip().register(webapp)
38
39    def finalizer():
40        gziptool.unregister()
41
42    request.addfinalizer(finalizer)
43
44    return gziptool
45
46
47def decompress(body):
48    import gzip
49
50    zbuf = BytesIO()
51    zbuf.write(body)
52    zbuf.seek(0)
53    zfile = gzip.GzipFile(mode='rb', fileobj=zbuf)
54    data = zfile.read()
55    zfile.close()
56    return data
57
58
59def test1(webapp, gziptool):
60    request = Request(webapp.server.http.base)
61    request.add_header("Accept-Encoding", "gzip")
62    opener = build_opener()
63
64    f = opener.open(request)
65    s = decompress(f.read())
66    assert s == b"Hello World!"
67
68
69def test2(webapp, gziptool):
70    request = Request("%s/static/largefile.txt" % webapp.server.http.base)
71    request.add_header("Accept-Encoding", "gzip")
72    opener = build_opener()
73
74    f = opener.open(request)
75    s = decompress(f.read())
76    assert s == open(path.join(DOCROOT, "largefile.txt"), "rb").read()