starlette/tests/test_routing.py

45 lines
1.0 KiB
Python
Raw Normal View History

2018-06-25 21:23:40 +00:00
from starlette import Response, Path, PathPrefix, Router, TestClient
def homepage(scope):
2018-06-25 21:26:01 +00:00
return Response("Hello, world", media_type="text/plain")
2018-06-25 21:23:40 +00:00
def users(scope):
2018-06-25 21:26:01 +00:00
return Response("All users", media_type="text/plain")
2018-06-25 21:23:40 +00:00
def user(scope):
2018-06-25 21:26:01 +00:00
content = "User " + scope["kwargs"]["username"]
return Response(content, media_type="text/plain")
2018-06-25 21:23:40 +00:00
2018-06-25 21:26:01 +00:00
app = Router(
[
Path("/", app=homepage),
PathPrefix(
"/users", app=Router([Path("", app=users), Path("/{username}", app=user)])
),
]
)
2018-06-25 21:23:40 +00:00
def test_router():
client = TestClient(app)
2018-06-25 21:26:01 +00:00
response = client.get("/")
2018-06-25 21:23:40 +00:00
assert response.status_code == 200
2018-06-25 21:26:01 +00:00
assert response.text == "Hello, world"
2018-06-25 21:23:40 +00:00
2018-06-25 21:26:01 +00:00
response = client.get("/foo")
2018-06-25 21:23:40 +00:00
assert response.status_code == 404
2018-06-25 21:26:01 +00:00
assert response.text == "Not found"
2018-06-25 21:23:40 +00:00
2018-06-25 21:26:01 +00:00
response = client.get("/users")
2018-06-25 21:23:40 +00:00
assert response.status_code == 200
2018-06-25 21:26:01 +00:00
assert response.text == "All users"
2018-06-25 21:23:40 +00:00
2018-06-25 21:26:01 +00:00
response = client.get("/users/tomchristie")
2018-06-25 21:23:40 +00:00
assert response.status_code == 200
2018-06-25 21:26:01 +00:00
assert response.text == "User tomchristie"