File: test_database.py

package info (click to toggle)
python-django-channels 4.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,036 kB
  • sloc: python: 3,109; makefile: 155; javascript: 60; sh: 8
file content (55 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download | duplicates (2)
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
from django import db
from django.test import TestCase

from channels.db import database_sync_to_async
from channels.generic.http import AsyncHttpConsumer
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.testing import HttpCommunicator, WebsocketCommunicator


@database_sync_to_async
def basic_query():
    with db.connections["default"].cursor() as cursor:
        cursor.execute("SELECT 1234")
        return cursor.fetchone()[0]


class WebsocketConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await basic_query()
        await self.accept("fun")


class HttpConsumer(AsyncHttpConsumer):
    async def handle(self, body):
        await basic_query()
        await self.send_response(
            200,
            b"",
            headers={b"Content-Type": b"text/plain"},
        )


class ConnectionClosingTests(TestCase):
    async def test_websocket(self):
        self.assertNotRegex(
            db.connections["default"].settings_dict.get("NAME"),
            "memorydb",
            "This bug only occurs when the database is materialized on disk",
        )
        communicator = WebsocketCommunicator(WebsocketConsumer.as_asgi(), "/")
        connected, subprotocol = await communicator.connect()
        self.assertTrue(connected)
        self.assertEqual(subprotocol, "fun")

    async def test_http(self):
        self.assertNotRegex(
            db.connections["default"].settings_dict.get("NAME"),
            "memorydb",
            "This bug only occurs when the database is materialized on disk",
        )
        communicator = HttpCommunicator(
            HttpConsumer.as_asgi(), method="GET", path="/test/"
        )
        connected = await communicator.get_response()
        self.assertTrue(connected)