Skip to content
This repository was archived by the owner on Jan 13, 2021. It is now read-only.

Commit bef5955

Browse files
committed
Connections are context managers.
Resolves #13.
1 parent d9b4f62 commit bef5955

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

HISTORY.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ X.X.X (XXXX-XX-XX)
99
- Implemented logging. (`Issue #12`_)
1010
- Stopped HTTP/2.0 special headers appearing in the response headers.
1111
(`Issue #16`_)
12+
- `HTTP20Connection` objects are now context managers. (`Issue #13`)
1213

1314

1415
.. _Issue #12: https://github.com/Lukasa/hyper/issues/12
1516
.. _Issue #16: https://github.com/Lukasa/hyper/issues/16
17+
.. _Issue #13: https://github.com/Lukasa/hyper/issues/13
1618

1719
0.0.1 (2014-02-11)
1820
++++++++++++++++++

hyper/http20/connection.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,3 +346,13 @@ def _recv_cb(self):
346346
self.streams[frame.stream_id].receive_frame(frame)
347347
else:
348348
self.receive_frame(frame)
349+
350+
351+
# The following two methods are the implementation of the context manager
352+
# protocol.
353+
def __enter__(self):
354+
return self
355+
356+
def __exit__(self, type, value, tb):
357+
self.close()
358+
return False # Never swallow exceptions.

test/test_integration.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,36 @@ def socket_handler(listener):
164164
assert len(frames[-1].data) == 64
165165

166166
self.tear_down()
167+
168+
def test_connection_context_manager(self):
169+
self.set_up()
170+
171+
data = []
172+
send_event = threading.Event()
173+
174+
def socket_handler(listener):
175+
sock = listener.accept()[0]
176+
177+
# We should get two packets: one connection header string, one
178+
# SettingsFrame.
179+
first = sock.recv(65535)
180+
second = sock.recv(65535)
181+
data.append(first)
182+
data.append(second)
183+
184+
# We need to send back a SettingsFrame.
185+
f = SettingsFrame(0)
186+
sock.send(f.serialize())
187+
188+
send_event.set()
189+
sock.close()
190+
191+
self._start_server(socket_handler)
192+
with HTTP20Connection(self.host, self.port) as conn:
193+
conn.connect()
194+
send_event.wait()
195+
196+
# Check that we closed the connection.
197+
assert conn._sock == None
198+
199+
self.tear_down()

0 commit comments

Comments
 (0)