File: test_blueprints.py

package info (click to toggle)
quart 0.20.0-4
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 1,888 kB
  • sloc: python: 8,644; makefile: 42; sh: 17; sql: 6
file content (467 lines) | stat: -rw-r--r-- 13,781 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
from __future__ import annotations

from typing import cast

import click
import pytest

from quart import abort
from quart import Blueprint
from quart import g
from quart import Quart
from quart import render_template_string
from quart import request
from quart import ResponseReturnValue
from quart import websocket
from quart.views import MethodView


async def test_blueprint_route() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    @blueprint.route("/page/")
    async def route() -> ResponseReturnValue:
        return "OK"

    app.register_blueprint(blueprint)

    async with app.test_request_context("/page/"):
        assert request.blueprint == "blueprint"


async def test_blueprint_websocket() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    @blueprint.websocket("/ws/")
    async def ws() -> None:
        while True:
            await websocket.send(websocket.blueprint.encode())

    app.register_blueprint(blueprint)

    test_client = app.test_client()
    async with test_client.websocket("/ws/") as test_websocket:
        result = await test_websocket.receive()
    assert cast(bytes, result) == b"blueprint"


async def test_blueprint_url_prefix() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)
    prefix = Blueprint("prefix", __name__, url_prefix="/prefix")

    @app.route("/page/")
    @blueprint.route("/page/")
    @prefix.route("/page/")
    async def route() -> ResponseReturnValue:
        return "OK"

    app.register_blueprint(blueprint, url_prefix="/blueprint")
    app.register_blueprint(prefix)

    async with app.test_request_context("/page/"):
        assert request.blueprint is None

    async with app.test_request_context("/prefix/page/"):
        assert request.blueprint == "prefix"

    async with app.test_request_context("/blueprint/page/"):
        assert request.blueprint == "blueprint"


async def test_empty_path_with_url_prefix() -> None:
    app = Quart(__name__)
    prefix = Blueprint("prefix", __name__, url_prefix="/prefix")

    @prefix.route("")
    async def empty_path_route() -> ResponseReturnValue:
        return "OK"

    app.register_blueprint(prefix)

    test_client = app.test_client()
    response = await test_client.get("/prefix")
    assert response.status_code == 200
    assert await response.get_data() == b"OK"


async def test_blueprint_template_filter() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    @blueprint.app_template_filter()
    def reverse(value: str) -> str:
        return value[::-1]

    @blueprint.route("/")
    async def route() -> ResponseReturnValue:
        return await render_template_string("{{ name|reverse }}", name="hello")

    app.register_blueprint(blueprint)

    response = await app.test_client().get("/")
    assert b"olleh" in (await response.get_data())


async def test_blueprint_error_handler() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    @blueprint.route("/error/")
    async def error() -> ResponseReturnValue:
        abort(409)
        return "OK"

    @blueprint.errorhandler(409)
    async def handler(_: Exception) -> ResponseReturnValue:
        return "Something Unique", 409

    app.register_blueprint(blueprint)

    response = await app.test_client().get("/error/")
    assert response.status_code == 409
    assert b"Something Unique" in (await response.get_data())


async def test_blueprint_method_view() -> None:
    app = Quart(__name__)
    blueprint = Blueprint("blueprint", __name__)

    class Views(MethodView):
        async def get(self) -> ResponseReturnValue:
            return "GET"

        async def post(self) -> ResponseReturnValue:
            return "POST"

    blueprint.add_url_rule("/", view_func=Views.as_view("simple"))

    app.register_blueprint(blueprint)

    test_client = app.test_client()
    response = await test_client.get("/")
    assert "GET" == (await response.get_data(as_text=True))
    response = await test_client.post("/")
    assert "POST" == (await response.get_data(as_text=True))


@pytest.mark.parametrize(
    "cli_group, args",
    [
        ("named", ["named", "cmd"]),
        (None, ["cmd"]),
        (Ellipsis, ["blueprint", "cmd"]),
    ],
)
def test_cli_blueprints(cli_group: str | None, args: list[str]) -> None:
    app = Quart(__name__)

    blueprint = Blueprint("blueprint", __name__, cli_group=cli_group)

    @blueprint.cli.command("cmd")
    def command() -> None:
        click.echo("command")

    app.register_blueprint(blueprint)

    app_runner = app.test_cli_runner()
    result = app_runner.invoke(args=args)

    assert "command" in result.output


@pytest.mark.parametrize(
    "parent_init, child_init, parent_registration, child_registration",
    [
        ("/parent", "/child", None, None),
        ("/parent", None, None, "/child"),
        (None, None, "/parent", "/child"),
        ("/other", "/something", "/parent", "/child"),
    ],
)
async def test_nesting_url_prefixes(
    parent_init: str | None,
    child_init: str | None,
    parent_registration: str | None,
    child_registration: str | None,
) -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix=parent_init)
    child = Blueprint("child", __name__, url_prefix=child_init)

    @child.route("/")
    def index() -> ResponseReturnValue:
        return "index"

    parent.register_blueprint(child, url_prefix=child_registration)
    app.register_blueprint(parent, url_prefix=parent_registration)

    test_client = app.test_client()
    response = await test_client.get("/parent/child/")
    assert response.status_code == 200


@pytest.mark.parametrize(
    "parent_subdomain, child_subdomain, expected_subdomain",
    [
        (None, None, None),
        ("parent", None, "parent"),
        (None, "child", "child"),
        ("parent", "child", "child.parent"),
    ],
)
async def test_nesting_subdomains(
    parent_subdomain: str | None,
    child_subdomain: str | None,
    expected_subdomain: str | None,
) -> None:
    app = Quart(__name__)
    domain_name = "domain.tld"
    app.config["SERVER_NAME"] = domain_name

    parent = Blueprint("parent", __name__, subdomain=parent_subdomain)
    child = Blueprint("child", __name__, subdomain=child_subdomain)

    @child.route("/")
    def index() -> ResponseReturnValue:
        return "index"

    parent.register_blueprint(child)
    app.register_blueprint(parent)

    test_client = app.test_client()
    response = await test_client.get("/", subdomain=expected_subdomain)
    assert response.status_code == 200


async def test_nesting_and_sibling() -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix="/parent")
    child = Blueprint("child", __name__, url_prefix="/child")

    @child.route("/")
    def index() -> ResponseReturnValue:
        return "index"

    parent.register_blueprint(child)
    app.register_blueprint(parent)
    app.register_blueprint(child, url_prefix="/sibling")

    test_client = app.test_client()
    response = await test_client.get("/parent/child/")
    assert response.status_code == 200
    response = await test_client.get("/sibling/")
    assert response.status_code == 200


def test_unique_blueprint_names() -> None:
    app = Quart(__name__)
    bp = Blueprint("bp", __name__)
    bp2 = Blueprint("bp", __name__)

    app.register_blueprint(bp)

    with pytest.raises(ValueError):
        app.register_blueprint(bp)

    with pytest.raises(ValueError):
        app.register_blueprint(bp2, url_prefix="/a")

    app.register_blueprint(bp, name="alt")


async def test_nested_blueprint() -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__, url_prefix="/parent")
    child = Blueprint("child", __name__)
    grandchild = Blueprint("grandchild", __name__)
    sibling = Blueprint("sibling", __name__)

    @parent.errorhandler(403)
    async def forbidden(_: Exception) -> ResponseReturnValue:
        return "Parent no", 403

    @parent.route("/")
    async def parent_index() -> ResponseReturnValue:
        return "Parent yes"

    @parent.route("/no")
    async def parent_no() -> ResponseReturnValue:
        abort(403)

    @child.route("/")
    async def child_index() -> ResponseReturnValue:
        return "Child yes"

    @child.route("/no")
    async def child_no() -> ResponseReturnValue:
        abort(403)

    @grandchild.errorhandler(403)
    async def grandchild_forbidden(_: Exception) -> ResponseReturnValue:
        return "Grandchild no", 403

    @grandchild.route("/")
    async def grandchild_index() -> ResponseReturnValue:
        return "Grandchild yes"

    @grandchild.route("/no")
    async def grandchild_no() -> ResponseReturnValue:
        abort(403)

    @sibling.route("/sibling")
    async def sibling_index() -> ResponseReturnValue:
        return "Sibling yes"

    child.register_blueprint(grandchild, url_prefix="/grandchild")
    parent.register_blueprint(child, url_prefix="/child")
    parent.register_blueprint(sibling)
    app.register_blueprint(parent)
    app.register_blueprint(parent, url_prefix="/alt", name="alt")

    client = app.test_client()

    assert (await (await client.get("/parent/")).get_data()) == b"Parent yes"
    assert (await (await client.get("/parent/child/")).get_data()) == b"Child yes"
    assert (await (await client.get("/parent/sibling")).get_data()) == b"Sibling yes"
    assert (await (await client.get("/alt/sibling")).get_data()) == b"Sibling yes"
    assert (
        await (await client.get("/parent/child/grandchild/")).get_data()
    ) == b"Grandchild yes"
    assert (await (await client.get("/parent/no")).get_data()) == b"Parent no"
    assert (await (await client.get("/parent/child/no")).get_data()) == b"Parent no"
    assert (
        await (await client.get("/parent/child/grandchild/no")).get_data()
    ) == b"Grandchild no"


async def test_blueprint_renaming() -> None:
    app = Quart(__name__)

    bp = Blueprint("bp", __name__)
    bp2 = Blueprint("bp2", __name__)

    @bp.get("/")
    async def index() -> str:
        return request.endpoint

    @bp.get("/error")
    async def error() -> str:
        abort(403)

    @bp.errorhandler(403)
    async def forbidden(_: Exception) -> ResponseReturnValue:
        return "Error", 403

    @bp2.get("/")
    async def index2() -> str:
        return request.endpoint

    bp.register_blueprint(bp2, url_prefix="/a", name="sub")
    app.register_blueprint(bp, url_prefix="/a")
    app.register_blueprint(bp, url_prefix="/b", name="alt")

    client = app.test_client()

    assert (await (await client.get("/a/")).get_data()) == b"bp.index"
    assert (await (await client.get("/b/")).get_data()) == b"alt.index"
    assert (await (await client.get("/a/a/")).get_data()) == b"bp.sub.index2"
    assert (await (await client.get("/b/a/")).get_data()) == b"alt.sub.index2"
    assert (await (await client.get("/a/error")).get_data()) == b"Error"
    assert (await (await client.get("/b/error")).get_data()) == b"Error"


def test_self_registration() -> None:
    bp = Blueprint("bp", __name__)

    with pytest.raises(ValueError):
        bp.register_blueprint(bp)


async def test_nested_callback_order() -> None:
    app = Quart(__name__)

    parent = Blueprint("parent", __name__)
    child = Blueprint("child", __name__)

    @app.before_request
    async def app_before1() -> None:
        g.setdefault("seen", []).append("app_1")

    @app.teardown_request
    async def app_teardown1(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "app_1"

    @app.before_request
    async def app_before2() -> None:
        g.setdefault("seen", []).append("app_2")

    @app.teardown_request
    async def app_teardown2(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "app_2"

    @app.context_processor
    async def app_ctx() -> dict:
        return dict(key="app")

    @parent.before_request
    async def parent_before1() -> None:
        g.setdefault("seen", []).append("parent_1")

    @parent.teardown_request
    async def parent_teardown1(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "parent_1"

    @parent.before_request
    async def parent_before2() -> None:
        g.setdefault("seen", []).append("parent_2")

    @parent.teardown_request
    async def parent_teardown2(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "parent_2"

    @parent.context_processor
    async def parent_ctx() -> dict:
        return dict(key="parent")

    @child.before_request
    async def child_before1() -> None:
        g.setdefault("seen", []).append("child_1")

    @child.teardown_request
    async def child_teardown1(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "child_1"

    @child.before_request
    async def child_before2() -> None:
        g.setdefault("seen", []).append("child_2")

    @child.teardown_request
    async def child_teardown2(exc: BaseException | None = None) -> None:
        assert g.seen.pop() == "child_2"

    @child.context_processor
    async def child_ctx() -> dict:
        return dict(key="child")

    @child.route("/a")
    async def a() -> str:
        return ", ".join(g.seen)

    @child.route("/b")
    async def b() -> str:
        return await render_template_string("{{ key }}")

    parent.register_blueprint(child)
    app.register_blueprint(parent)

    client = app.test_client()
    assert (
        await (await client.get("/a")).get_data()
    ) == b"app_1, app_2, parent_1, parent_2, child_1, child_2"
    assert (await (await client.get("/b")).get_data()) == b"child"