| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2014 The LUCI Authors. All rights reserved. |
| 2 # Use of this source code is governed under the Apache License, Version 2.0 |
| 3 # that can be found in the LICENSE file. |
| 4 |
| 5 import BaseHTTPServer |
| 6 import json |
| 7 import logging |
| 8 import threading |
| 9 import urllib2 |
| 10 |
| 11 |
| 12 class MockHandler(BaseHTTPServer.BaseHTTPRequestHandler): |
| 13 def _json(self, data): |
| 14 """Sends a JSON response.""" |
| 15 self.send_response(200) |
| 16 self.send_header('Content-type', 'application/json') |
| 17 self.end_headers() |
| 18 json.dump(data, self.wfile) |
| 19 |
| 20 def _octet_stream(self, data): |
| 21 """Sends a binary response.""" |
| 22 self.send_response(200) |
| 23 self.send_header('Content-type', 'application/octet-stream') |
| 24 self.end_headers() |
| 25 self.wfile.write(data) |
| 26 |
| 27 def _read_body(self): |
| 28 """Reads the request body.""" |
| 29 return self.rfile.read(int(self.headers['Content-Length'])) |
| 30 |
| 31 def _drop_body(self): |
| 32 """Reads the request body.""" |
| 33 size = int(self.headers['Content-Length']) |
| 34 while size: |
| 35 chunk = min(4096, size) |
| 36 self.rfile.read(chunk) |
| 37 size -= chunk |
| 38 |
| 39 def log_message(self, fmt, *args): |
| 40 logging.info( |
| 41 '%s - - [%s] %s', self.address_string(), self.log_date_time_string(), |
| 42 fmt % args) |
| 43 |
| 44 |
| 45 class MockServer(object): |
| 46 _HANDLER_CLS = None |
| 47 |
| 48 def __init__(self): |
| 49 self._closed = False |
| 50 self._server = BaseHTTPServer.HTTPServer( |
| 51 ('127.0.0.1', 0), self._HANDLER_CLS) |
| 52 self._server.url = self.url = 'http://localhost:%d' % ( |
| 53 self._server.server_port) |
| 54 self._thread = threading.Thread(target=self._run, name='httpd') |
| 55 self._thread.daemon = True |
| 56 self._thread.start() |
| 57 logging.info('%s', self.url) |
| 58 |
| 59 def close(self): |
| 60 self.close_start() |
| 61 self.close_end() |
| 62 |
| 63 def close_start(self): |
| 64 assert not self._closed |
| 65 self._closed = True |
| 66 urllib2.urlopen(self.url + '/on/quit') |
| 67 |
| 68 def close_end(self): |
| 69 assert self._closed |
| 70 self._thread.join() |
| 71 |
| 72 def _run(self): |
| 73 while not self._closed: |
| 74 self._server.handle_request() |
| OLD | NEW |