A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.

0 downloads

dbbasic-web/tests/test_asgi.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Quellhorst Replace multipart parser with stdlib-only implementation eb957a2 9 months, 2 weeks ago History
test_asgi.py · 3.7 KB · 143 lines
1"""Tests for dbbasic_web.asgi module"""
2import pytest
3from dbbasic_web.asgi import app
4
5
6class MockReceive:
7 """Mock ASGI receive callable"""
8
9 def __init__(self, body: bytes = b""):
10 self.body = body
11 self.called = False
12
13 async def __call__(self):
14 if not self.called:
15 self.called = True
16 return {
17 "type": "http.request",
18 "body": self.body,
19 "more_body": False
20 }
21 return {"type": "http.disconnect"}
22
23
24class MockSend:
25 """Mock ASGI send callable"""
26
27 def __init__(self):
28 self.messages = []
29
30 async def __call__(self, message):
31 self.messages.append(message)
32
33 @property
34 def status(self):
35 """Get response status code"""
36 for msg in self.messages:
37 if msg["type"] == "http.response.start":
38 return msg["status"]
39 return None
40
41 @property
42 def headers(self):
43 """Get response headers as dict"""
44 for msg in self.messages:
45 if msg["type"] == "http.response.start":
46 return {
47 k.decode() if isinstance(k, bytes) else k:
48 v.decode() if isinstance(v, bytes) else v
49 for k, v in msg.get("headers", [])
50 }
51 return {}
52
53 @property
54 def body(self):
55 """Get response body"""
56 body_parts = []
57 for msg in self.messages:
58 if msg["type"] == "http.response.body":
59 body_parts.append(msg.get("body", b""))
60 return b"".join(body_parts)
61
62
63@pytest.mark.asyncio
64class TestAsgiApp:
65 """Test ASGI application"""
66
67 async def test_404_for_unknown_path(self):
68 """Unknown path should return 404"""
69 scope = {
70 "type": "http",
71 "method": "GET",
72 "path": "/nonexistent/path/that/does/not/exist",
73 "query_string": b"",
74 "headers": [],
75 }
76 receive = MockReceive()
77 send = MockSend()
78
79 await app(scope, receive, send)
80
81 assert send.status == 404
82
83 async def test_http_request_reads_body(self):
84 """HTTP handler should read request body"""
85 scope = {
86 "type": "http",
87 "method": "POST",
88 "path": "/test",
89 "query_string": b"",
90 "headers": [],
91 }
92 receive = MockReceive(body=b"test body content")
93 send = MockSend()
94
95 await app(scope, receive, send)
96
97 # Just verify it didn't crash and returned something
98 assert send.status is not None
99
100 async def test_response_headers_encoded(self):
101 """Response headers should be bytes"""
102 scope = {
103 "type": "http",
104 "method": "GET",
105 "path": "/nonexistent",
106 "query_string": b"",
107 "headers": [],
108 }
109 receive = MockReceive()
110 send = MockSend()
111
112 await app(scope, receive, send)
113
114 # Check that response was sent
115 assert len(send.messages) >= 1
116 assert send.messages[0]["type"] == "http.response.start"
117
118
119@pytest.mark.asyncio
120class TestLifespanHandler:
121 """Test ASGI lifespan handling"""
122
123 async def test_lifespan_startup(self):
124 """Lifespan startup should complete"""
125 scope = {"type": "lifespan"}
126
127 messages = [
128 {"type": "lifespan.startup"},
129 {"type": "lifespan.shutdown"},
130 ]
131 message_iter = iter(messages)
132
133 async def receive():
134 return next(message_iter)
135
136 sent = []
137 async def send(message):
138 sent.append(message)
139
140 await app(scope, receive, send)
141
142 assert {"type": "lifespan.startup.complete"} in sent
143 assert {"type": "lifespan.shutdown.complete"} in sent