sanic/tests/test_vhosts.py

57 lines
1.6 KiB
Python
Raw Permalink Normal View History

2021-02-07 09:38:37 +00:00
import pytest
from sanic_routing.exceptions import RouteExists
2021-02-08 10:18:29 +00:00
from sanic import Sanic
2018-08-26 15:43:14 +01:00
from sanic.response import text
2017-01-08 23:48:12 +00:00
2021-02-08 10:18:29 +00:00
def test_vhosts():
app = Sanic("app")
2018-12-30 11:18:06 +00:00
@app.route("/", host="example.com")
2018-10-22 21:25:38 +01:00
async def handler1(request):
2017-01-08 23:48:12 +00:00
return text("You're at example.com!")
2018-12-30 11:18:06 +00:00
@app.route("/", host="subdomain.example.com")
2018-10-22 21:25:38 +01:00
async def handler2(request):
2017-01-08 23:48:12 +00:00
return text("You're at subdomain.example.com!")
headers = {"Host": "example.com"}
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/", headers=headers)
2017-01-08 23:48:12 +00:00
assert response.text == "You're at example.com!"
headers = {"Host": "subdomain.example.com"}
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/", headers=headers)
2017-01-08 23:48:12 +00:00
assert response.text == "You're at subdomain.example.com!"
2017-01-19 03:40:20 +00:00
2018-08-26 15:43:14 +01:00
def test_vhosts_with_list(app):
2018-12-30 11:18:06 +00:00
@app.route("/", host=["hello.com", "world.com"])
2017-01-19 03:40:20 +00:00
async def handler(request):
return text("Hello, world!")
headers = {"Host": "hello.com"}
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/", headers=headers)
2017-01-19 03:40:20 +00:00
assert response.text == "Hello, world!"
headers = {"Host": "world.com"}
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/", headers=headers)
2017-01-19 03:40:20 +00:00
assert response.text == "Hello, world!"
2017-02-21 00:36:48 +00:00
2018-08-26 15:43:14 +01:00
def test_vhosts_with_defaults(app):
2018-12-30 11:18:06 +00:00
@app.route("/", host="hello.com")
2018-10-22 21:25:38 +01:00
async def handler1(request):
2017-02-21 00:36:48 +00:00
return text("Hello, world!")
2021-02-07 09:38:37 +00:00
with pytest.raises(RouteExists):
@app.route("/")
async def handler2(request):
return text("default")
2017-02-21 00:36:48 +00:00
headers = {"Host": "hello.com"}
2018-12-30 11:18:06 +00:00
request, response = app.test_client.get("/", headers=headers)
2017-02-21 00:36:48 +00:00
assert response.text == "Hello, world!"