Skip to content

Commit 664b111

Browse files
authored
Merge pull request #93 from StephenBrown2/format_examples
Format bench, examples, fuzz
2 parents 41a3467 + 5542487 commit 664b111

File tree

7 files changed

+91
-71
lines changed

7 files changed

+91
-71
lines changed

CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ other hand, the following are all very welcome:
4747
[isort](https://github.com/timothycrosley/isort) as configured in
4848
the project. With those projects installed the commands,
4949

50-
black h11/
51-
isort --dont-skip __init__.py --apply --settings-path setup.cfg --recursive h11
50+
black h11/ bench/ examples/ fuzz/
51+
isort --dont-skip __init__.py --apply --settings-path setup.cfg --recursive h11 bench examples fuzz
5252

5353
will format your code for you.
5454

bench/benchmarks/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-

bench/benchmarks/benchmarks.py

Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,55 +3,65 @@
33

44
import h11
55

6+
67
# Basic ASV benchmark of core functionality
78
def time_server_basic_get_with_realistic_headers():
89
c = h11.Connection(h11.SERVER)
9-
c.receive_data(b"GET / HTTP/1.1\r\n"
10-
b"Host: example.com\r\n"
11-
b"User-Agent: Mozilla/5.0 (X11; Linux x86_64; "
12-
b"rv:45.0) Gecko/20100101 Firefox/45.0\r\n"
13-
b"Accept: text/html,application/xhtml+xml,"
14-
b"application/xml;q=0.9,*/*;q=0.8\r\n"
15-
b"Accept-Language: en-US,en;q=0.5\r\n"
16-
b"Accept-Encoding: gzip, deflate, br\r\n"
17-
b"DNT: 1\r\n"
18-
b"Cookie: ID=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
19-
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
20-
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
21-
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
22-
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"
23-
b"Connection: keep-alive\r\n\r\n")
10+
c.receive_data(
11+
b"GET / HTTP/1.1\r\n"
12+
b"Host: example.com\r\n"
13+
b"User-Agent: Mozilla/5.0 (X11; Linux x86_64; "
14+
b"rv:45.0) Gecko/20100101 Firefox/45.0\r\n"
15+
b"Accept: text/html,application/xhtml+xml,"
16+
b"application/xml;q=0.9,*/*;q=0.8\r\n"
17+
b"Accept-Language: en-US,en;q=0.5\r\n"
18+
b"Accept-Encoding: gzip, deflate, br\r\n"
19+
b"DNT: 1\r\n"
20+
b"Cookie: ID=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
21+
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
22+
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
23+
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
24+
b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"
25+
b"Connection: keep-alive\r\n\r\n"
26+
)
2427
while True:
2528
event = c.next_event()
2629
if event is h11.NEED_DATA:
2730
break
2831

29-
c.send(h11.Response(status_code=200,
30-
headers=[
31-
(b"Cache-Control", b"private, max-age=0"),
32-
(b"Content-Encoding", b"gzip"),
33-
(b"Content-Type", b"text/html; charset=UTF-8"),
34-
(b"Date", b"Fri, 20 May 2016 09:23:41 GMT"),
35-
(b"Expires", b"-1"),
36-
(b"Server", b"gws"),
37-
(b"X-Frame-Options", b"SAMEORIGIN"),
38-
(b"X-XSS-Protection", b"1; mode=block"),
39-
(b"Content-Length", b"1000"),
40-
]))
32+
c.send(
33+
h11.Response(
34+
status_code=200,
35+
headers=[
36+
(b"Cache-Control", b"private, max-age=0"),
37+
(b"Content-Encoding", b"gzip"),
38+
(b"Content-Type", b"text/html; charset=UTF-8"),
39+
(b"Date", b"Fri, 20 May 2016 09:23:41 GMT"),
40+
(b"Expires", b"-1"),
41+
(b"Server", b"gws"),
42+
(b"X-Frame-Options", b"SAMEORIGIN"),
43+
(b"X-XSS-Protection", b"1; mode=block"),
44+
(b"Content-Length", b"1000"),
45+
],
46+
)
47+
)
4148
c.send(h11.Data(data=b"x" * 1000))
4249
c.send(h11.EndOfMessage())
4350

51+
4452
# Useful for manual benchmarking, e.g. with vmprof or on PyPy
4553
def _run_basic_get_repeatedly():
4654
from timeit import default_timer
55+
4756
REPEAT = 10000
48-
#while True:
57+
# while True:
4958
for _ in range(7):
5059
start = default_timer()
5160
for _ in range(REPEAT):
5261
time_server_basic_get_with_realistic_headers()
5362
finish = default_timer()
5463
print("{:.1f} requests/sec".format(REPEAT / (finish - start)))
5564

65+
5666
if __name__ == "__main__":
5767
_run_basic_get_repeatedly()

examples/basic-client.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import socket
22
import ssl
3+
34
import h11
45

56
################################################################
@@ -8,13 +9,15 @@
89

910
conn = h11.Connection(our_role=h11.CLIENT)
1011
ctx = ssl.create_default_context()
11-
sock = ctx.wrap_socket(socket.create_connection(("httpbin.org", 443)),
12-
server_hostname="httpbin.org")
12+
sock = ctx.wrap_socket(
13+
socket.create_connection(("httpbin.org", 443)), server_hostname="httpbin.org"
14+
)
1315

1416
################################################################
1517
# Sending a request
1618
################################################################
1719

20+
1821
def send(event):
1922
print("Sending event:")
2023
print(event)
@@ -24,16 +27,21 @@ def send(event):
2427
# Send the resulting bytes on the wire
2528
sock.sendall(data)
2629

27-
send(h11.Request(method="GET",
28-
target="/get",
29-
headers=[("Host", "httpbin.org"),
30-
("Connection", "close")]))
30+
31+
send(
32+
h11.Request(
33+
method="GET",
34+
target="/get",
35+
headers=[("Host", "httpbin.org"), ("Connection", "close")],
36+
)
37+
)
3138
send(h11.EndOfMessage())
3239

3340
################################################################
3441
# Receiving the response
3542
################################################################
3643

44+
3745
def next_event():
3846
while True:
3947
# Check if an event is already available
@@ -47,6 +55,7 @@ def next_event():
4755
continue
4856
return event
4957

58+
5059
while True:
5160
event = next_event()
5261
print("Received event:")

examples/trio-server.py

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@
7979
from itertools import count
8080
from wsgiref.handlers import format_date_time
8181

82-
import trio
8382
import h11
83+
import trio
8484

8585
MAX_RECV = 2 ** 16
8686
TIMEOUT = 10
@@ -99,10 +99,9 @@ def __init__(self, stream):
9999
self.stream = stream
100100
self.conn = h11.Connection(h11.SERVER)
101101
# Our Server: header
102-
self.ident = " ".join([
103-
"h11-example-trio-server/{}".format(h11.__version__),
104-
h11.PRODUCT_ID,
105-
]).encode("ascii")
102+
self.ident = " ".join(
103+
["h11-example-trio-server/{}".format(h11.__version__), h11.PRODUCT_ID]
104+
).encode("ascii")
106105
# A unique id for this connection, to include in debugging output
107106
# (useful for understanding what's going on if there are multiple
108107
# simultaneous clients).
@@ -120,8 +119,8 @@ async def _read_from_peer(self):
120119
if self.conn.they_are_waiting_for_100_continue:
121120
self.info("Sending 100 Continue")
122121
go_ahead = h11.InformationalResponse(
123-
status_code=100,
124-
headers=self.basic_headers())
122+
status_code=100, headers=self.basic_headers()
123+
)
125124
await self.send(go_ahead)
126125
try:
127126
data = await self.stream.receive_some(MAX_RECV)
@@ -185,6 +184,7 @@ def info(self, *args):
185184
# Little debugging method
186185
print("{}:".format(self._obj_id), *args)
187186

187+
188188
################################################################
189189
# Server main loop
190190
################################################################
@@ -218,8 +218,7 @@ async def http_serve(stream):
218218
wrapper = TrioHTTPWrapper(stream)
219219
wrapper.info("Got new connection")
220220
while True:
221-
assert wrapper.conn.states == {
222-
h11.CLIENT: h11.IDLE, h11.SERVER: h11.IDLE}
221+
assert wrapper.conn.states == {h11.CLIENT: h11.IDLE, h11.SERVER: h11.IDLE}
223222

224223
try:
225224
with trio.fail_after(TIMEOUT):
@@ -244,19 +243,19 @@ async def http_serve(stream):
244243
states = wrapper.conn.states
245244
wrapper.info("unexpected state", states, "-- bailing out")
246245
await maybe_send_error_response(
247-
wrapper,
248-
RuntimeError("unexpected state {}".format(states)))
246+
wrapper, RuntimeError("unexpected state {}".format(states))
247+
)
249248
await wrapper.shutdown_and_clean_up()
250249
return
251250

251+
252252
################################################################
253253
# Actual response handlers
254254
################################################################
255255

256256
# Helper function
257257
async def send_simple_response(wrapper, status_code, content_type, body):
258-
wrapper.info("Sending", status_code,
259-
"response with", len(body), "bytes")
258+
wrapper.info("Sending", status_code, "response with", len(body), "bytes")
260259
headers = wrapper.basic_headers()
261260
headers.append(("Content-Type", content_type))
262261
headers.append(("Content-Length", str(len(body))))
@@ -265,12 +264,12 @@ async def send_simple_response(wrapper, status_code, content_type, body):
265264
await wrapper.send(h11.Data(data=body))
266265
await wrapper.send(h11.EndOfMessage())
267266

267+
268268
async def maybe_send_error_response(wrapper, exc):
269269
# If we can't send an error, oh well, nothing to be done
270270
wrapper.info("trying to send error response...")
271271
if wrapper.conn.our_state not in {h11.IDLE, h11.SEND_RESPONSE}:
272-
wrapper.info("...but I can't, because our state is",
273-
wrapper.conn.our_state)
272+
wrapper.info("...but I can't, because our state is", wrapper.conn.our_state)
274273
return
275274
try:
276275
if isinstance(exc, h11.RemoteProtocolError):
@@ -280,13 +279,13 @@ async def maybe_send_error_response(wrapper, exc):
280279
else:
281280
status_code = 500
282281
body = str(exc).encode("utf-8")
283-
await send_simple_response(wrapper,
284-
status_code,
285-
"text/plain; charset=utf-8",
286-
body)
282+
await send_simple_response(
283+
wrapper, status_code, "text/plain; charset=utf-8", body
284+
)
287285
except Exception as exc:
288286
wrapper.info("error while sending error response:", exc)
289287

288+
290289
async def send_echo_response(wrapper, request):
291290
wrapper.info("Preparing echo response")
292291
if request.method not in {b"GET", b"POST"}:
@@ -296,8 +295,10 @@ async def send_echo_response(wrapper, request):
296295
response_json = {
297296
"method": request.method.decode("ascii"),
298297
"target": request.target.decode("ascii"),
299-
"headers": [(name.decode("ascii"), value.decode("ascii"))
300-
for (name, value) in request.headers],
298+
"headers": [
299+
(name.decode("ascii"), value.decode("ascii"))
300+
for (name, value) in request.headers
301+
],
301302
"body": "",
302303
}
303304
while True:
@@ -306,15 +307,14 @@ async def send_echo_response(wrapper, request):
306307
break
307308
assert type(event) is h11.Data
308309
response_json["body"] += event.data.decode("ascii")
309-
response_body_unicode = json.dumps(response_json,
310-
sort_keys=True,
311-
indent=4,
312-
separators=(",", ": "))
310+
response_body_unicode = json.dumps(
311+
response_json, sort_keys=True, indent=4, separators=(",", ": ")
312+
)
313313
response_body_bytes = response_body_unicode.encode("utf-8")
314-
await send_simple_response(wrapper,
315-
200,
316-
"application/json; charset=utf-8",
317-
response_body_bytes)
314+
await send_simple_response(
315+
wrapper, 200, "application/json; charset=utf-8", response_body_bytes
316+
)
317+
318318

319319
async def serve(port):
320320
print("listening on http://localhost:{}".format(port))
@@ -323,6 +323,7 @@ async def serve(port):
323323
except KeyboardInterrupt:
324324
print("KeyboardInterrupt - shutting down")
325325

326+
326327
################################################################
327328
# Run the server
328329
################################################################

fuzz/afl-server.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22
# either successfully parse it, or else throw a RemoteProtocolError, never any
33
# other error.
44

5-
import sys
65
import os
6+
import sys
77

88
import afl
9-
109
import h11
1110

1211
if sys.version_info[0] >= 3:
1312
in_file = sys.stdin.detach()
1413
else:
1514
in_file = sys.stdin
1615

16+
1717
def process_all(c):
1818
while True:
1919
event = c.next_event()
@@ -22,6 +22,7 @@ def process_all(c):
2222
if type(event) is h11.ConnectionClosed:
2323
break
2424

25+
2526
afl.init()
2627

2728
data = in_file.read()
@@ -40,7 +41,7 @@ def process_all(c):
4041
server2 = h11.Connection(h11.SERVER)
4142
try:
4243
for i in range(len(data)):
43-
server2.receive_data(data[i:i + 1])
44+
server2.receive_data(data[i : i + 1])
4445
process_all(server2)
4546
server2.receive_data(b"")
4647
process_all(server2)

tox.ini

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,5 @@ deps =
1111
black
1212
isort
1313
commands =
14-
black --check --diff h11/
15-
isort --dont-skip __init__.py --diff --check --settings-path setup.cfg --recursive h11
14+
black --check --diff h11/ bench/ examples/ fuzz/
15+
isort --dont-skip __init__.py --diff --check --settings-path setup.cfg --recursive h11 bench examples fuzz

0 commit comments

Comments
 (0)