Skip to content

Instantly share code, notes, and snippets.

@mre
Last active December 5, 2019 10:12
Show Gist options
  • Select an option

  • Save mre/8175a83e4753ca25225e to your computer and use it in GitHub Desktop.

Select an option

Save mre/8175a83e4753ca25225e to your computer and use it in GitHub Desktop.
How to write a unit test for BaseHTTPServer and subclasses
import threading
import time
import unittest
import urllib2
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('it works!')
class TestRequests(unittest.TestCase):
def test_single_request(self):
server = HTTPServer(("127.0.0.1", 12345), MyHandler)
server_thread = threading.Thread(target=server.serve_forever)
# Also tried this:
#server_thread.setDaemon(True)
server_thread.start()
# Wait a bit for the server to come up
time.sleep(1)
print urllib2.urlopen("http://localhost:12345/").read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment