Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add handler names for websockets for url_for usage #1880

Merged
merged 1 commit into from
Jun 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions sanic/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,13 @@ def websocket(
strict_slashes = self.strict_slashes

def decorator(handler):
nonlocal uri
nonlocal host
nonlocal strict_slashes
nonlocal version
nonlocal name

name = f"{self.name}.{name or handler.__name__}"
route = FutureRoute(
handler, uri, [], host, strict_slashes, False, version, name
)
Expand Down
18 changes: 15 additions & 3 deletions tests/test_blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,11 @@ def handler2(request):


def test_bp_with_host_list(app):
bp = Blueprint("test_bp_host", url_prefix="/test1", host=["example.com", "sub.example.com"])
bp = Blueprint(
"test_bp_host",
url_prefix="/test1",
host=["example.com", "sub.example.com"],
)

@bp.route("/")
def handler1(request):
Expand All @@ -279,8 +283,16 @@ def handler2(request):


def test_several_bp_with_host_list(app):
bp = Blueprint("test_text", url_prefix="/test", host=["example.com", "sub.example.com"])
bp2 = Blueprint("test_text2", url_prefix="/test", host=["sub1.example.com", "sub2.example.com"])
bp = Blueprint(
"test_text",
url_prefix="/test",
host=["example.com", "sub.example.com"],
)
bp2 = Blueprint(
"test_text2",
url_prefix="/test",
host=["sub1.example.com", "sub2.example.com"],
)

@bp.route("/")
def handler(request):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,11 @@ def test_pickle_app_with_bp(app, protocol):
assert up_p_app.is_request_stream is False
assert response.text == "Hello"


@pytest.mark.parametrize("protocol", [3, 4])
def test_pickle_app_with_static(app, protocol):
app.route("/")(handler)
app.static('/static', "/tmp/static")
app.static("/static", "/tmp/static")
p_app = pickle.dumps(app, protocol=protocol)
del app
up_p_app = pickle.loads(p_app)
Expand Down
36 changes: 27 additions & 9 deletions tests/test_reloader.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import os
import secrets
import sys
from contextlib import suppress

from contextlib import suppress
from subprocess import PIPE, Popen, TimeoutExpired
from tempfile import TemporaryDirectory
from textwrap import dedent
Expand All @@ -23,16 +23,20 @@
except ImportError:
flags = 0


def terminate(proc):
if flags:
proc.send_signal(CTRL_BREAK_EVENT)
else:
proc.terminate()


def write_app(filename, **runargs):
text = secrets.token_urlsafe()
with open(filename, "w") as f:
f.write(dedent(f"""\
f.write(
dedent(
f"""\
Comment on lines +37 to +39
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose this was by linter because the original formatting was better. Maybe reindent the rest of the string literal too to match the extra level at opening?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. make fix-import

Oh trust in the almighty black.

import os
from sanic import Sanic

Expand All @@ -45,9 +49,11 @@ def complete(*args):
if __name__ == "__main__":
app.run(**{runargs!r})
"""
))
)
)
return text


def scanner(proc):
for line in proc.stdout:
line = line.decode().strip()
Expand All @@ -59,14 +65,26 @@ def scanner(proc):
argv = dict(
script=[sys.executable, "reloader.py"],
module=[sys.executable, "-m", "reloader"],
sanic=[sys.executable, "-m", "sanic", "--port", "42104", "--debug", "reloader.app"],
sanic=[
sys.executable,
"-m",
"sanic",
"--port",
"42104",
"--debug",
"reloader.app",
],
)

@pytest.mark.parametrize("runargs, mode", [
(dict(port=42102, auto_reload=True), "script"),
(dict(port=42103, debug=True), "module"),
(dict(), "sanic"),
])

@pytest.mark.parametrize(
"runargs, mode",
[
(dict(port=42102, auto_reload=True), "script"),
(dict(port=42103, debug=True), "module"),
(dict(), "sanic"),
],
)
async def test_reloader_live(runargs, mode):
with TemporaryDirectory() as tmpdir:
filename = os.path.join(tmpdir, "reloader.py")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ def test_response_body_bytes_deprecated(app):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")

HTTPResponse(body_bytes=b'bytes')
HTTPResponse(body_bytes=b"bytes")

assert len(w) == 1
assert issubclass(w[0].category, DeprecationWarning)
Expand Down
48 changes: 48 additions & 0 deletions tests/test_url_for.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import asyncio

from sanic.blueprints import Blueprint


def test_routes_with_host(app):
@app.route("/")
@app.route("/", name="hostindex", host="example.com")
Expand All @@ -13,3 +18,46 @@ def index(request):
app.url_for("hostpath", _external=True)
== "http://path.example.com/path"
)


def test_websocket_bp_route_name(app):
"""Tests that blueprint websocket route is named."""
event = asyncio.Event()
bp = Blueprint("test_bp", url_prefix="/bp")

@bp.get("/main")
async def main(request):
...

@bp.websocket("/route")
async def test_route(request, ws):
event.set()

@bp.websocket("/route2")
async def test_route2(request, ws):
event.set()

@bp.websocket("/route3", name="foobar_3")
async def test_route3(request, ws):
event.set()

app.blueprint(bp)

uri = app.url_for("test_bp.main")
assert uri == "/bp/main"

uri = app.url_for("test_bp.test_route")
assert uri == "/bp/route"
request, response = app.test_client.websocket(uri)
assert response.opened is True
assert event.is_set()

event.clear()
uri = app.url_for("test_bp.test_route2")
assert uri == "/bp/route2"
request, response = app.test_client.websocket(uri)
assert response.opened is True
assert event.is_set()

uri = app.url_for("test_bp.foobar_3")
assert uri == "/bp/route3"