|
| 1 | +from django import db |
| 2 | +from django.test import TestCase |
| 3 | + |
| 4 | +from channels.db import database_sync_to_async |
| 5 | +from channels.generic.http import AsyncHttpConsumer |
| 6 | +from channels.generic.websocket import AsyncWebsocketConsumer |
| 7 | +from channels.testing import HttpCommunicator, WebsocketCommunicator |
| 8 | + |
| 9 | + |
| 10 | +@database_sync_to_async |
| 11 | +def basic_query(): |
| 12 | + with db.connections["default"].cursor() as cursor: |
| 13 | + cursor.execute("SELECT 1234") |
| 14 | + return cursor.fetchone()[0] |
| 15 | + |
| 16 | + |
| 17 | +class WebsocketConsumer(AsyncWebsocketConsumer): |
| 18 | + async def connect(self): |
| 19 | + await basic_query() |
| 20 | + await self.accept("fun") |
| 21 | + |
| 22 | + |
| 23 | +class HttpConsumer(AsyncHttpConsumer): |
| 24 | + async def handle(self, body): |
| 25 | + await basic_query() |
| 26 | + await self.send_response( |
| 27 | + 200, |
| 28 | + b"", |
| 29 | + headers={b"Content-Type": b"text/plain"}, |
| 30 | + ) |
| 31 | + |
| 32 | + |
| 33 | +class ConnectionClosingTests(TestCase): |
| 34 | + async def test_websocket(self): |
| 35 | + self.assertNotRegex( |
| 36 | + db.connections["default"].settings_dict.get("NAME"), |
| 37 | + "memorydb", |
| 38 | + "This bug only occurs when the database is materialized on disk", |
| 39 | + ) |
| 40 | + communicator = WebsocketCommunicator(WebsocketConsumer.as_asgi(), "/") |
| 41 | + connected, subprotocol = await communicator.connect() |
| 42 | + self.assertTrue(connected) |
| 43 | + self.assertEqual(subprotocol, "fun") |
| 44 | + |
| 45 | + async def test_http(self): |
| 46 | + self.assertNotRegex( |
| 47 | + db.connections["default"].settings_dict.get("NAME"), |
| 48 | + "memorydb", |
| 49 | + "This bug only occurs when the database is materialized on disk", |
| 50 | + ) |
| 51 | + communicator = HttpCommunicator( |
| 52 | + HttpConsumer.as_asgi(), method="GET", path="/test/" |
| 53 | + ) |
| 54 | + connected = await communicator.get_response() |
| 55 | + self.assertTrue(connected) |
0 commit comments