|
| 1 | +from typing import Type |
| 2 | + |
| 3 | +from sanic import Blueprint, Sanic, text |
| 4 | + |
| 5 | + |
| 6 | +def factory(sanic_cls: Type[Sanic], blueprint_cls: Type[Blueprint]): |
| 7 | + app = sanic_cls("Foo") |
| 8 | + bp = blueprint_cls("Bar", url_prefix="/bar") |
| 9 | + |
| 10 | + @app.get("/") |
| 11 | + async def handler(request): |
| 12 | + return text(request.name) |
| 13 | + |
| 14 | + @bp.get("/") |
| 15 | + async def handler(request): # noqa: F811 // Intentionally reused handler name |
| 16 | + return text(request.name) |
| 17 | + |
| 18 | + app.blueprint(bp) |
| 19 | + |
| 20 | + return app |
| 21 | + |
| 22 | + |
| 23 | +def test_vanilla_sanic(): |
| 24 | + app = factory(Sanic, Blueprint) |
| 25 | + _, foo_response = app.test_client.get("/") |
| 26 | + _, bar_response = app.test_client.get("/bar/") |
| 27 | + |
| 28 | + assert foo_response.text == "Foo.handler" |
| 29 | + assert bar_response.text == "Foo.Bar.handler" |
| 30 | + |
| 31 | + |
| 32 | +def test_custom_app(): |
| 33 | + class Custom(Sanic): |
| 34 | + def generate_name(self, *objects): |
| 35 | + existing = self._generate_name(*objects) |
| 36 | + return existing.replace("Foo", "CHANGED_APP") |
| 37 | + |
| 38 | + app = factory(Custom, Blueprint) |
| 39 | + _, foo_response = app.test_client.get("/") |
| 40 | + _, bar_response = app.test_client.get("/bar/") |
| 41 | + |
| 42 | + assert foo_response.text == "CHANGED_APP.handler" |
| 43 | + assert bar_response.text == "CHANGED_APP.Bar.handler" |
| 44 | + |
| 45 | + |
| 46 | +def test_custom_blueprint(): |
| 47 | + class Custom(Blueprint): |
| 48 | + def generate_name(self, *objects): |
| 49 | + existing = self._generate_name(*objects) |
| 50 | + return existing.replace("Bar", "CHANGED_BP") |
| 51 | + |
| 52 | + app = factory(Sanic, Custom) |
| 53 | + _, foo_response = app.test_client.get("/") |
| 54 | + _, bar_response = app.test_client.get("/bar/") |
| 55 | + |
| 56 | + assert foo_response.text == "Foo.handler" |
| 57 | + assert bar_response.text == "Foo.CHANGED_BP.handler" |
0 commit comments