def test_recipe_book(app: App, client, numbers): app.recipe(numbers) response = client.get("/numbers/integers/3.5") assert response.status_code == 200 assert response.json() == {"value": 3} response = client.get("/numbers/floats/1") assert response.status_code == 200 assert response.json() == {"value": 1.0}
def test_if_prefix_not_given_then_routes_mounted_at_slash_name(app: App): numbers = Recipe("numbers") @numbers.route("/real") async def real(req, res): pass app.recipe(numbers) assert app.url_for("numbers:real") == "/numbers/real"
def test_if_prefix_then_routes_mounted_at_prefix(app: App): numbers = Recipe("numbers", prefix="/numbers-yo") @numbers.route("/real") async def real(req, res): pass app.recipe(numbers) assert app.url_for("numbers:real") == "/numbers-yo/real"
def test_websocket_recipe_route(app: App, client): chat = Recipe("chat") @chat.websocket_route("/room/{name}", receive_type="json", send_type="text") async def chat_room(ws: WebSocket, name: str): message = await ws.receive() await ws.send(f"[{name}]: {message['text']}") app.recipe(chat) with client.websocket_connect("/chat/room/test") as ws: ws.send_json({"text": "Hello"}) assert ws.receive_text() == "[test]: Hello"
def test_redirect(app: App, client): numbers = Recipe("numbers") @numbers.route("/R") async def R(req, res): numbers.redirect(name="numbers:real") @numbers.route("/real") async def real(req, res): res.text = "inf" app.recipe(numbers) response = client.get("/numbers/R") assert response.status_code == 200 assert response.text == "inf"
# 👇 Executes `requires_token()` before the view @courses.route("/top") @hooks.before(requires_token) async def get_top_courses(req, res): try: # Query parameters! n = int(req.query_params.get("n")) except TypeError: n = 5 courses = [storage.get(pk)._asdict() for pk in analytics.top(n=n)] res.media = courses # Mounts the routes of `courses` at `/courses` on `app` app.recipe(courses) # Custom error handlers! @app.error_handler(HTTPError) def handle_json(req, res, exc): res.media = { "error": exc.status_phrase, "status": exc.status_code, "message": "Duh!", } res.status_code = exc.status_code if __name__ == "__main__": app.run()