mock_tracker.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import json
  2. import socketserver
  3. import threading
  4. from terroroftinytown.six.moves.BaseHTTPServer import (HTTPServer,
  5. BaseHTTPRequestHandler)
  6. class TrackerHandler(BaseHTTPRequestHandler):
  7. def do_GET(self):
  8. if self.path == '/':
  9. self.send_response(200)
  10. self.end_headers()
  11. self.wfile.write(b'Mock Tracker')
  12. else:
  13. self.send_response(404)
  14. self.end_headers()
  15. def do_POST(self):
  16. if self.path == '/api/get':
  17. self.send_response(200)
  18. self.end_headers()
  19. self.wfile.write(json.dumps({
  20. 'tamper_key': '1FECB1D2DC40CF446700B875B1E738A6',
  21. 'ip_address': None,
  22. 'id': 7,
  23. 'username': 'SMAUG',
  24. 'datetime_claimed': 1407026018,
  25. 'lower_sequence_num': 0,
  26. 'upper_sequence_num': 20,
  27. 'project': {
  28. 'url_template': 'http://chfoo-d1.mooo.com:8060/{shortcode}',
  29. 'request_delay': 1.0,
  30. 'min_version': '',
  31. 'custom_code_required': False,
  32. 'body_regex': '<a id="redir_link" href="[^"]+">',
  33. 'method': 'get',
  34. 'redirect_codes': [301, 302],
  35. 'alphabet': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
  36. 'no_redirect_codes': [404],
  37. 'name': 'test_project',
  38. 'banned_codes': [420],
  39. 'unavailable_codes': [200]
  40. }
  41. }).encode('ascii'))
  42. elif self.path == '/api/done':
  43. self.send_response(200)
  44. self.end_headers()
  45. self.wfile.write(json.dumps(
  46. {'status': 'OK'}
  47. ).encode('ascii'))
  48. else:
  49. self.send_response(404)
  50. self.end_headers()
  51. class MockTracker(socketserver.ThreadingMixIn, HTTPServer):
  52. def __init__(self, address):
  53. HTTPServer.__init__(self, address, TrackerHandler)
  54. class MockTrackerThread(threading.Thread):
  55. def __init__(self, port=0):
  56. threading.Thread.__init__(self)
  57. self.daemon = True
  58. self._port = port
  59. self._server = MockTracker(('0.0.0.0', self._port))
  60. self._port = self._server.server_address[1]
  61. self.started_event = threading.Event()
  62. def run(self):
  63. self.started_event.set()
  64. self._server.serve_forever()
  65. def stop(self):
  66. self._server.shutdown()
  67. @property
  68. def port(self):
  69. return self._port
  70. if __name__ == '__main__':
  71. server = MockTrackerThread(8059)
  72. server.start()
  73. server.join()