starlette/tests/middleware/test_gzip.py

77 lines
2.4 KiB
Python
Raw Normal View History

2018-10-15 11:08:10 +00:00
from starlette.applications import Starlette
from starlette.middleware.gzip import GZipMiddleware
from starlette.responses import PlainTextResponse, StreamingResponse
def test_gzip_responses(test_client_factory):
2018-10-15 11:08:10 +00:00
app = Starlette()
app.add_middleware(GZipMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("x" * 4000, status_code=200)
client = test_client_factory(app)
2018-10-15 11:08:10 +00:00
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "gzip"
assert int(response.headers["Content-Length"]) < 4000
def test_gzip_not_in_accept_encoding(test_client_factory):
2018-10-15 11:08:10 +00:00
app = Starlette()
app.add_middleware(GZipMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("x" * 4000, status_code=200)
client = test_client_factory(app)
2018-10-15 11:08:10 +00:00
response = client.get("/", headers={"accept-encoding": "identity"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert "Content-Encoding" not in response.headers
assert int(response.headers["Content-Length"]) == 4000
def test_gzip_ignored_for_small_responses(test_client_factory):
2018-10-15 11:08:10 +00:00
app = Starlette()
app.add_middleware(GZipMiddleware)
@app.route("/")
def homepage(request):
return PlainTextResponse("OK", status_code=200)
client = test_client_factory(app)
2018-10-15 11:08:10 +00:00
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "OK"
assert "Content-Encoding" not in response.headers
assert int(response.headers["Content-Length"]) == 2
def test_gzip_streaming_response(test_client_factory):
2018-10-15 11:08:10 +00:00
app = Starlette()
app.add_middleware(GZipMiddleware)
@app.route("/")
def homepage(request):
async def generator(bytes, count):
for index in range(count):
yield bytes
streaming = generator(bytes=b"x" * 400, count=10)
return StreamingResponse(streaming, status_code=200)
client = test_client_factory(app)
2018-10-15 11:08:10 +00:00
response = client.get("/", headers={"accept-encoding": "gzip"})
assert response.status_code == 200
assert response.text == "x" * 4000
assert response.headers["Content-Encoding"] == "gzip"
assert "Content-Length" not in response.headers