|
1 | 1 | import pytest |
| 2 | +from django.test import override_settings |
2 | 3 |
|
3 | 4 | from channels.generic.websocket import AsyncWebsocketConsumer |
4 | | -from channels.security.websocket import OriginValidator |
| 5 | +from channels.security.websocket import ( |
| 6 | + AllowedHostsOriginValidator, |
| 7 | + OriginValidator, |
| 8 | +) |
5 | 9 | from channels.testing import WebsocketCommunicator |
6 | 10 |
|
7 | 11 |
|
| 12 | +@pytest.mark.django_db(transaction=True) |
| 13 | +@pytest.mark.asyncio |
| 14 | +async def test_allowed_hosts_origin_validator(): |
| 15 | + """ |
| 16 | + Tests that AllowedHostsOriginValidator correctly allows/denies connections. |
| 17 | + """ |
| 18 | + with override_settings( |
| 19 | + DEBUG=True, |
| 20 | + ALLOWED_HOSTS=[], |
| 21 | + ): |
| 22 | + # Make our test application |
| 23 | + application = AllowedHostsOriginValidator(AsyncWebsocketConsumer()) |
| 24 | + # Test a subdomain of localhost |
| 25 | + communicator = WebsocketCommunicator( |
| 26 | + application, "/", headers=[(b"origin", b"http://subdomain.localhost:8000")] |
| 27 | + ) |
| 28 | + connected, _ = await communicator.connect() |
| 29 | + assert connected |
| 30 | + await communicator.disconnect() |
| 31 | + # Test a bad connection |
| 32 | + communicator = WebsocketCommunicator( |
| 33 | + application, "/", headers=[(b"origin", b"http://bad-domain.com")] |
| 34 | + ) |
| 35 | + connected, _ = await communicator.connect() |
| 36 | + assert not connected |
| 37 | + await communicator.disconnect() |
| 38 | + |
| 39 | + |
8 | 40 | @pytest.mark.django_db(transaction=True) |
9 | 41 | @pytest.mark.asyncio |
10 | 42 | async def test_origin_validator(): |
|
0 commit comments