Debian Codegraph @

tests/servers/test_basehttp.py

raw
1 from io import BytesIO
2 from socketserver import ThreadingMixIn
3
4 from django.core.handlers.wsgi import WSGIRequest
5 from django.core.servers.basehttp import WSGIRequestHandler, WSGIServer
6 from django.test import SimpleTestCase
7 from django.test.client import RequestFactory
8 from django.test.utils import captured_stderr
9
10
11 class Stub(ThreadingMixIn):
12 def __init__(self, **kwargs):
13 self.__dict__.update(kwargs)
14
15 def sendall(self, data):
16 self.makefile("wb").write(data)
17
18
19 class UnclosableBytesIO(BytesIO):
20 def close(self):
21 # WSGIRequestHandler closes the output file; we need to make this a
22 # no-op so we can still read its contents.
23 pass
24
25
26 class WSGIRequestHandlerTestCase(SimpleTestCase):
27 request_factory = RequestFactory()
28
29 def test_log_message(self):
30 request = WSGIRequest(self.request_factory.get("/").environ)
31 request.makefile = lambda *args, **kwargs: BytesIO()
32 handler = WSGIRequestHandler(request, "192.168.0.2", None)
33 level_status_codes = {
34 "info": [200, 301, 304],
35 "warning": [400, 403, 404],
36 "error": [500, 503],
37 }
38 for level, status_codes in level_status_codes.items():
39 for status_code in status_codes:
40 # The correct level gets the message.
41 with self.assertLogs("django.server", level.upper()) as cm:
42 handler.log_message("GET %s %s", "A", str(status_code))
43 self.assertIn("GET A %d" % status_code, cm.output[0])
44 # Incorrect levels don't have any messages.
45 for wrong_level in level_status_codes:
46 if wrong_level != level:
47 with self.assertLogs("django.server", "INFO") as cm:
48 handler.log_message("GET %s %s", "A", str(status_code))
49 self.assertNotEqual(
50 cm.records[0].levelname, wrong_level.upper()
51 )
52
53 def test_https(self):
54 request = WSGIRequest(self.request_factory.get("/").environ)
55 request.makefile = lambda *args, **kwargs: BytesIO()
56
57 handler = WSGIRequestHandler(request, "192.168.0.2", None)
58
59 with self.assertLogs("django.server", "ERROR") as cm:
60 handler.log_message("GET %s %s", "\x16\x03", "4")
61 self.assertEqual(
62 "You're accessing the development server over HTTPS, "
63 "but it only supports HTTP.",
64 cm.records[0].getMessage(),
65 )
66
67 def test_strips_underscore_headers(self):
68 """WSGIRequestHandler ignores headers containing underscores.
69
70 This follows the lead of nginx and Apache 2.4, and is to avoid
71 ambiguity between dashes and underscores in mapping to WSGI environ,
72 which can have security implications.
73 """
74
75 def test_app(environ, start_response):
76 """A WSGI app that just reflects its HTTP environ."""
77 start_response("200 OK", [])
78 http_environ_items = sorted(
79 "%s:%s" % (k, v) for k, v in environ.items() if k.startswith("HTTP_")
80 )
81 yield (",".join(http_environ_items)).encode()
82
83 rfile = BytesIO()
84 rfile.write(b"GET / HTTP/1.0\r\n")
85 rfile.write(b"Some-Header: good\r\n")
86 rfile.write(b"Some_Header: bad\r\n")
87 rfile.write(b"Other_Header: bad\r\n")
88 rfile.seek(0)
89
90 wfile = UnclosableBytesIO()
91
92 def makefile(mode, *a, **kw):
93 if mode == "rb":
94 return rfile
95 elif mode == "wb":
96 return wfile
97
98 request = Stub(makefile=makefile)
99 server = Stub(base_environ={}, get_app=lambda: test_app)
100
101 # Prevent logging from appearing in test output.
102 with self.assertLogs("django.server", "INFO"):
103 # instantiating a handler runs the request as side effect
104 WSGIRequestHandler(request, "192.168.0.2", server)
105
106 wfile.seek(0)
107 body = list(wfile.readlines())[-1]
108
109 self.assertEqual(body, b"HTTP_SOME_HEADER:good")
110
111 def test_no_body_returned_for_head_requests(self):
112 hello_world_body = b"<!DOCTYPE html><html><body>Hello World</body></html>"
113 content_length = len(hello_world_body)
114
115 def test_app(environ, start_response):
116 """A WSGI app that returns a hello world."""
117 start_response("200 OK", [])
118 return [hello_world_body]
119
120 rfile = BytesIO(b"GET / HTTP/1.0\r\n")
121 rfile.seek(0)
122
123 wfile = UnclosableBytesIO()
124
125 def makefile(mode, *a, **kw):
126 if mode == "rb":
127 return rfile
128 elif mode == "wb":
129 return wfile
130
131 request = Stub(makefile=makefile)
132 server = Stub(base_environ={}, get_app=lambda: test_app)
133
134 # Prevent logging from appearing in test output.
135 with self.assertLogs("django.server", "INFO"):
136 # Instantiating a handler runs the request as side effect.
137 WSGIRequestHandler(request, "192.168.0.2", server)
138
139 wfile.seek(0)
140 lines = list(wfile.readlines())
141 body = lines[-1]
142 # The body is returned in a GET response.
143 self.assertEqual(body, hello_world_body)
144 self.assertIn(f"Content-Length: {content_length}\r\n".encode(), lines)
145 self.assertNotIn(b"Connection: close\r\n", lines)
146
147 rfile = BytesIO(b"HEAD / HTTP/1.0\r\n")
148 rfile.seek(0)
149 wfile = UnclosableBytesIO()
150
151 with self.assertLogs("django.server", "INFO"):
152 WSGIRequestHandler(request, "192.168.0.2", server)
153
154 wfile.seek(0)
155 lines = list(wfile.readlines())
156 body = lines[-1]
157 # The body is not returned in a HEAD response.
158 self.assertEqual(body, b"\r\n")
159 self.assertIs(
160 any([line.startswith(b"Content-Length:") for line in lines]), False
161 )
162 self.assertNotIn(b"Connection: close\r\n", lines)
163
164 def test_non_zero_content_length_set_head_request(self):
165 hello_world_body = b"<!DOCTYPE html><html><body>Hello World</body></html>"
166 content_length = len(hello_world_body)
167
168 def test_app(environ, start_response):
169 """
170 A WSGI app that returns a hello world with non-zero Content-Length.
171 """
172 start_response("200 OK", [("Content-length", str(content_length))])
173 return [hello_world_body]
174
175 rfile = BytesIO(b"HEAD / HTTP/1.0\r\n")
176 rfile.seek(0)
177
178 wfile = UnclosableBytesIO()
179
180 def makefile(mode, *a, **kw):
181 if mode == "rb":
182 return rfile
183 elif mode == "wb":
184 return wfile
185
186 request = Stub(makefile=makefile)
187 server = Stub(base_environ={}, get_app=lambda: test_app)
188
189 # Prevent logging from appearing in test output.
190 with self.assertLogs("django.server", "INFO"):
191 # Instantiating a handler runs the request as side effect.
192 WSGIRequestHandler(request, "192.168.0.2", server)
193
194 wfile.seek(0)
195 lines = list(wfile.readlines())
196 body = lines[-1]
197 # The body is not returned in a HEAD response.
198 self.assertEqual(body, b"\r\n")
199 # Non-zero Content-Length is not removed.
200 self.assertEqual(lines[-2], f"Content-length: {content_length}\r\n".encode())
201 self.assertNotIn(b"Connection: close\r\n", lines)
202
203
204 class WSGIServerTestCase(SimpleTestCase):
205 request_factory = RequestFactory()
206
207 def test_broken_pipe_errors(self):
208 """WSGIServer handles broken pipe errors."""
209 request = WSGIRequest(self.request_factory.get("/").environ)
210 client_address = ("192.168.2.0", 8080)
211 msg = f"- Broken pipe from {client_address}"
212 tests = [
213 BrokenPipeError,
214 ConnectionAbortedError,
215 ConnectionResetError,
216 ]
217 for exception in tests:
218 with self.subTest(exception=exception):
219 try:
220 server = WSGIServer(("localhost", 0), WSGIRequestHandler)
221 try:
222 raise exception()
223 except Exception:
224 with captured_stderr() as err:
225 with self.assertLogs("django.server", "INFO") as cm:
226 server.handle_error(request, client_address)
227 self.assertEqual(err.getvalue(), "")
228 self.assertEqual(cm.records[0].getMessage(), msg)
229 finally:
230 server.server_close()