167
167
self.credentials.append([realm, host, username, password])
170
class RecordingServer(object):
171
"""A fake HTTP server.
173
It records the bytes sent to it, and replies with a 200.
176
def __init__(self, expect_body_tail=None):
179
:type expect_body_tail: str
180
:param expect_body_tail: a reply won't be sent until this string is
183
self._expect_body_tail = expect_body_tail
186
self.received_bytes = ''
189
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
190
self._sock.bind(('127.0.0.1', 0))
191
self.host, self.port = self._sock.getsockname()
192
self._ready = threading.Event()
193
self._thread = threading.Thread(target=self._accept_read_and_reply)
194
self._thread.setDaemon(True)
198
def _accept_read_and_reply(self):
201
self._sock.settimeout(5)
203
conn, address = self._sock.accept()
204
# On win32, the accepted connection will be non-blocking to start
205
# with because we're using settimeout.
206
conn.setblocking(True)
207
while not self.received_bytes.endswith(self._expect_body_tail):
208
self.received_bytes += conn.recv(4096)
209
conn.sendall('HTTP/1.1 200 OK\r\n')
210
except socket.timeout:
211
# Make sure the client isn't stuck waiting for us to e.g. accept.
214
# The client may have already closed the socket.
221
# We might have already closed it. We don't care.
170
227
class TestHTTPServer(tests.TestCase):
171
228
"""Test the HTTP servers implementations."""
422
479
class TestPost(tests.TestCase):
424
481
def test_post_body_is_received(self):
425
server = http_utils.RecordingServer(expect_body_tail='end-of-body')
482
server = RecordingServer(expect_body_tail='end-of-body')
427
484
self.addCleanup(server.tearDown)
428
485
scheme = self._qualified_prefix
639
696
class TestRecordingServer(tests.TestCase):
641
698
def test_create(self):
642
server = http_utils.RecordingServer(expect_body_tail=None)
699
server = RecordingServer(expect_body_tail=None)
643
700
self.assertEqual('', server.received_bytes)
644
701
self.assertEqual(None, server.host)
645
702
self.assertEqual(None, server.port)
647
704
def test_setUp_and_tearDown(self):
648
server = http_utils.RecordingServer(expect_body_tail=None)
705
server = RecordingServer(expect_body_tail=None)
651
708
self.assertNotEqual(None, server.host)
656
713
self.assertEqual(None, server.port)
658
715
def test_send_receive_bytes(self):
659
server = http_utils.RecordingServer(expect_body_tail='c')
716
server = RecordingServer(expect_body_tail='c')
661
718
self.addCleanup(server.tearDown)
662
719
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)